-3

please, How do you explain technically why P =2 and not P=3. (I tried it on Geany and it have the value 2).

int main()
{
    int N = 10, P = 5, Q = 10;
    N = 5;
    P = 2;
    Q = ++N == 3 && P++ != 3;
    printf ("N=%d P=%d Q=%d\n", N, P, Q);
    return 0;
}

thanks for your response.

Tamir Vered
  • 10,187
  • 5
  • 45
  • 57
OntoBLW
  • 215
  • 1
  • 2
  • 6
  • what is the problem with &&? How can I precisely explain to someone beginner in C langage this issue? I tried to do inverse like this Q = ++N != 3 && P++ == 3 so I obtained 3 in P. – OntoBLW Oct 05 '15 at 13:57

4 Answers4

2

Because in this case (P++ != 3) you sum the value (++) after of the realize the comparison between P and 3.

If case of you use this type of comparison (++P != 3) the sum is before of the comparison.

The point is that is not the same (P++ != 3) and (++P != 3).

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
ber2008
  • 323
  • 3
  • 10
  • Although correct, this is not the right answer for the question. I mean, the same result is obtained when replacing `(P++ != 3;)` with `(++P != 3;)` See other answers for the reason. – Spikatrix Oct 05 '15 at 14:43
1

C11 standard states:

6.5.13 Logical AND operator

4 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.

So, basically only ++N == 3 is being executed. And it's result is doomed always to be false. So, right part of Your AND operation is just skipped.

As noted in comments, this kind of behaviour is called Short-circuit evaluation.

Community
  • 1
  • 1
Kamiccolo
  • 7,758
  • 3
  • 34
  • 47
1
Q = ++N == 3 && P++ != 3;

The first expression (++N == 3) is false, thus the program never even executes the second expression. This phenomenon is called Short Circuit Evaluation

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Magisch
  • 7,312
  • 9
  • 36
  • 52
0
/*
because in line
*/
Q = ++N == 3 && P++ != 3;

/*
you are not affecting any thing to P;

because true= true && true;
false= either both false or one of them is false
the compiler if it find any of the arguments false then it stops there and returns false.
it is mater of speed so if :
*/
Q=++N==3 && DoSomeThing();
/*
the function DoSomeThing() will never be called 
because ++N (which is now 6) do not equals 3;

but this will succeed obviously
*/

Q=++N==6 && DoSomeThing();
milevyo
  • 2,165
  • 1
  • 13
  • 18