Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short circuit evaluation of a statement with ++ operator in C

I have executed the following code in Code::Blocks 10.05 on Windows 7.

int a=0,b=0,c;
c=a++&&b++;
printf("\na=%d\nb=%d\nc=%d\n\n",a,b,c);

The output I obtained is given below,

a=1
b=0
c=0

This makes perfect sense because of short circuit evaluation.

The expression a++ is post increment and 0 is returned to the logical and (&&). Hence the part b++ is not evaluated since both 0 && 0 and 0 && 1 evaluates to 0.

But here arises my doubt. The precedence value of operators clearly states that ++ is having higher precedence over &&. So my understanding was like this, both a++ and b++ are evaluated and then && only checks the result of expression a++ to come to a decision. But this has not happened only a++ is evaluated here.

What is the reason for this behavior? Does && being a sequence point has something to do with this behavior? If so why we say that && is having lower precedence than ++?

like image 685
Deepu Avatar asked Aug 03 '15 04:08

Deepu


People also ask

What is short-circuit evaluation in the case of the and operator?

Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first ...

What are short circuit operators in C?

Like C, Perl provides the && (logical AND) and || (logical OR) operators. They evaluate from left to right (with && having slightly higher precedence than || ) testing the truth of the statement.

Which operator can be used to do a short-circuit evaluation?

The logical AND operator performs short-circuit evaluation: if the left-hand operand is false, the right-hand expression is not evaluated. The logical OR operator also performs short-circuit evaluation: if the left-hand operand is true, the right-hand expression is not evaluated.

What are logical operators in C language evaluated with the short-circuit?

Do logical operators in the C language are evaluated with the short circuit? Explanation: None.


1 Answers

You are confused about precedence and order of evaluation.

Precedence defines how the operators are grouped, i.e

c = a++ && b++;

is equivalent to:

c = ((a++) && (b++));

Order of evaluation defines how the expression is evaluated, the short circuit of && means a++ is evaluated first, if it's zero, the end; if it's not zero, b++ is then evaluated.


As another example:

c = (a++) + (b++);

Is a++ evaluated before b++? The answer is we don't know. Most operators don't define the order of evaluation. && is one of the few operators that do define. (The rest are ||, , and ?:)

like image 181
Yu Hao Avatar answered Sep 21 '22 05:09

Yu Hao