Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment operator in C

Tags:

c

I tried the following code snippet:

void main()
{
    int x = 1,y = 1,z = 1;
    ++x || ++y && ++z;
    printf("x = %d\ny = %d\nz = %d\n",x,y,z);
}

The output I expected was:

x = 2
y = 2
z = 2

But I am getting the output:

x = 2
y = 1
z = 1

What is the reason for this?

like image 439
Leo Messi Avatar asked Dec 12 '22 08:12

Leo Messi


2 Answers

This is because of short-circuiting.

http://en.wikipedia.org/wiki/Short-circuit_evaluation

When this is evaluated:

++x || ++y && ++z;

The first part ++x already determines the value of the entire expression. So the ++y && ++z is not executed at all. So the side-effects of ++y and ++z are not invoked.

like image 160
Mysticial Avatar answered Dec 22 '22 00:12

Mysticial


The result of ++x is nonzero, so evaluates to true, so short-circuits the || operator. ++y && ++z is not executed.

like image 37
ObscureRobot Avatar answered Dec 21 '22 23:12

ObscureRobot