Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C if statement with && - Which function will execute first?

Tags:

c

if-statement

If I have an if statement in C that looks like:

if( function1() > 0 && function2() > 0 ){

    //blah

}

Which function will execute first and will it always execute in that order?

like image 790
PJT Avatar asked Nov 28 '11 18:11

PJT


1 Answers

Here function1() is guaranteed to execute first.

The && operator is a short-circuiting operator. function2() won't even be called unless the result of function1() is greater than zero.

From the C99 standard:

Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares equal to 0, the second operand is not evaluated.

like image 119
Mark Byers Avatar answered Oct 17 '22 03:10

Mark Byers