You are here:

C/c language

Advertisement


Question
respected sir namaskar,
sir if i write the following;

{
int i=2, j=-1, k=3, a;
a= ++i || ++j && ++k;
printf ("%d  %d  %d",i, j, k);
}
i get the answer :
i=3 j=-1  and k=3


sir, as a general rule && is executed before the evaluation of || so the answer should have been

i=2  j=0  and k =3
but it is not happening . Why the precedence rule is not being followed here.

thanks for listening.  

Answer
Here is how it happens:
Depending on the order of precedence, your expression will be grouped like this:
a = ++i || (++j && ++k);
Here there are two expressions and will be evaluated from left to right.
Since ++i tests positive, the rightmost expression will never get executed!
So, you end up with values i=3, j=-1 and k=3.

If you just want to test the operator precedence it is ok.
But, if you want to do serious programming, then use parentheses and you will never get into all this confusion.

-ssnkumar

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.