cant understand this code

R

ravindradivekar

Hi everyone,
can someone explain this code to me?

a=1, b=1, c=1;

c = --a&&b++;

After this statement b=2 according to me, but the result is b=1;
Why?

Regards,
Ravindra
 
I

Ike Naar

Hi everyone,
can someone explain this code to me?

a=1, b=1, c=1;

c = --a&&b++;

After this statement b=2 according to me, but the result is b=1;
Why?

The && operator does not evaluate its right operand if the left
operand equals zero.
 
K

Kaz Kylheku

Hi everyone,
can someone explain this code to me?

a=1, b=1, c=1;

c = --a&&b++;

After this statement b=2 according to me, but the result is b=1;
Why?

The right hand side of the && operator is only evaluated if the left hand side
yields true (nonzero).

The left hand side is --a . This means "decrement a and yield the new value".
The new value is zero.

Since the value left of && is zero, the right hand side is not evaluated.
And so the action b++ never happens.
 
J

James Kuyper

Hi everyone,
can someone explain this code to me?

a=1, b=1, c=1;

c = --a&&b++;

After this statement b=2 according to me, but the result is b=1;
Why?

That very compact statement is equivalent to the following expanded version:

a = a - 1;
if(a != 0)
{
if(b != 0)
c = 1;
else
c = 0;
b = b + 1;
}
else
c = 0;

Do you understand why that results in b==1? Do you understand why this
expanded version is equivalent to your more compact code?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top