+ 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;

12th Feb 2018, 9:23 PM
Miroslav M
Miroslav M - avatar
6 odpowiedzi
+ 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.
12th Feb 2018, 9:36 PM
jay
jay - avatar
+ 8
Yes, Only 0 is considered false.
12th Feb 2018, 9:45 PM
jay
jay - avatar
+ 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.
12th Feb 2018, 9:57 PM
jay
jay - avatar
+ 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.
12th Feb 2018, 9:55 PM
Vlad Serbu
Vlad Serbu - avatar
+ 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
12th Feb 2018, 10:04 PM
Vlad Serbu
Vlad Serbu - avatar
+ 3
Great thanks, so any non-zero is True? Even the negative numbers? I must have missed that in C++ course.. :(
12th Feb 2018, 9:38 PM
Miroslav M
Miroslav M - avatar