+ 3
IF statement with number in condition (c++)
Can you please explain, how come you can use integer in IF condition? What is tested here? How it works? And what it is even good for? Thanks! For example: if (28) cout << x; else cout << y;
6 Answers
+ 9
if() tests for a true/false condition. A boolean is usually used (or something which equates to a true false condition) But since a boolean (in c) is just an integer range limited between 0 and 1 any integer can be substituted in its place.
Using the if statement like you have has no use as any non zero number is considered true as a result the else statement will never be executed.
+ 8
Yes, Only 0 is considered false.
+ 8
The more you know, thanks Vlad!
From: https://en.m.wikipedia.org/wiki/Boolean_data_type
C++ has a separate Boolean data type bool, but with automatic conversions from scalar and pointer values that are very similar to those of C.
+ 4
@jay
It's not like booleans are integers. It's that if() expects an integer (because C didn't have booleans for a long time) so if you feed it a boolean it automatically converts it into an integer.
@rudolf
while(i-- > 0)
There, done with a boolean.
+ 4
@jay
C (since C99) also has a boolean type. It's called _Bool. And you can use the bool, true and false keywords using stdbool.h
+ 3
Great thanks, so any non-zero is True? Even the negative numbers?
I must have missed that in C++ course.. :(