A silly question

Why is the result 7 ?
1
2
3
4
5
6
7
8
9
10
11
  int main()
{
	int i = 6, value;
	if ((++i > 7) && (i++ < 8))
		value = 1;
	else
		value = 2;

	printf("%d\n", i);
	return 0;
}

It shouldn't be 8 ?
If is 7 why ?

Thank you ! :)
Hi,

The first part of the if is false, so the second part is not evaluated (both must be true).

Also, avoid having more than one ++i per statement - there is no guarantee which order these are evaluated in, so this leads to undefined behaviour.
As TIM said different compilers will evaluate this differently. For eg.
1
2
int c=5;
cout<<c+++++c;


will output different numbers on different compilers
Last edited on
I was thinking that it doesn't evaluate anymore after the first part of if, but I wasn't sure.
Thank you very much guys. :)
It wasn't a silly question at all! I looked at it and wondered myself until I remembered what TIM said about, "short circuiting." It's actually a VERY valuable thing to remember, and also holds true for or (||) as well:

1
2
3
4
5
int a{1};
int b{0};
if(a || b){
   //Will ALWAYS evaluate true; it won't even evaluate b!
}


Contrast that with:

1
2
3
4
5
int a{1};
int b{0};
if(b || a){
   //Will ALWAYS evaluate true, but WILL test a!
}
Topic archived. No new replies allowed.