Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Logical Comparison as conditional statement?

Ran across some code that used this, which led me to wonder.

if(condition) foo = bar();

condition && (foo = bar());

Are these two segments of code equal to a compiler? If not, in what ways would they differ?

like image 509
Anne Quinn Avatar asked Sep 29 '11 09:09

Anne Quinn


People also ask

How do you write a conditional statement in C?

C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

What does #if mean in C?

In the C Programming Language, the #if directive allows for conditional compilation. The preprocessor evaluates an expression provided with the #if directive to determine if the subsequent code should be included in the compilation process.

Can you nest if statements in C?

Yes, both C and C++ allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement.

What are the three types of conditional statements?

Conditional Statements : if, else, switch.


1 Answers

Due to operator precendence, the latter is interpreted as:

(condition && foo) = bar();

Additionally, there is a possibility of && being overloaded, which may result in pretty much anything.

So in short: they are not equal at all - at least in general case.

like image 160
Xion Avatar answered Sep 23 '22 15:09

Xion