views:

190

answers:

2

Does the following code invoke UB ?

int main(){
  volatile int i = 0;
  volatile int* p = &i;
  int j = ++i * *p;
}
+9  A: 

Yes - either ++i or *p (which is i) can be evaluated first.

anon
but regardless of order of evaluation the result would be same right?
Red Hyena
No. If ++i is evaluated first, you have 1 * 1. If *p is evaluated first, you have 1 * 0.
anon
Oops! How could I not notice that! Thanks for the response!
Red Hyena
Remember that this isn't just unspecified, it's undefined. It will almost certainly return 0 or 1 on all systems I'm familiar with, and keep on going, but that isn't a language guarantee.
David Thornley
@David Yes indeed. I should have pointed that out in my answer.
anon
+10  A: 

Yes that is Undefined Behavior because you are trying to violate the second rule..

The Standard states that

1) Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.

2) Furthermore, the prior value shall be accessed only to determine the value to be stored.

Note: The order of evaluation of the operands of * operator is unspecified and *p is nothing but i.

Prasoon Saurav
You mean `*` operator I guess...
Red Hyena
Yeah typo :P....... edited my post :)
Prasoon Saurav
@Prasoon : It is not right to edit others' posts just to format their code with your favorite style of indentation. Haven't you read the StackOverflow guidelines - "Respect the original author" ? (>_<)
Red Hyena