Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is i = 0, ++i defined?

Tags:

I recently learned about the , operator and the fact that it introduces a sequence point.

I also learned that the following code led to undefined behavior:

i = ++i; 

Because i was modified twice between two sequence points.

But what about the following codes ?

i = 0, ++i; i = (0, ++i); 

While I know the rules, I can't get to a conclusion. So is it defined behavior or not ?

edit: Just as @paxdiablo mentions, defined or not, this is really a bad practice which should be avoided. This question is asked solely for educational purposes and better understanding of the "rules".

like image 463
ereOn Avatar asked Oct 18 '10 12:10

ereOn


People also ask

Is 1 0 not defined or infinity?

In mathematics, expressions like 1/0 are undefined. But the limit of the expression 1/x as x tends to zero is infinity.

Why 0 is not defined?

Because what happens is that if we can say that zero, 5, or basically any number, then that means that that "c" is not unique. So, in this scenario the first part doesn't work. So, that means that this is going to be undefined. So zero divided by zero is undefined.

Is 0 defined?

0 is the integer immediately preceding 1. Zero is an even number because it is divisible by 2 with no remainder. 0 is neither positive nor negative, or both positive and negative. Many definitions include 0 as a natural number, in which case it is the only natural number that is not positive.

Is Infinity * 0 defined?

∞0 is an indeterminate form, that is, the value can't be determined exactly.


2 Answers

Yes. = has higher precedence than ,, so this expression is equivalent to (i = 0), ++i. , is a sequence point, so it's guaranteed that the ++i occurs after the assignment.

I'm not sure whether i = (0, ++i) is defined though. My guess would be no; there's no sequence point between the increment and the assignment.

like image 79
Oliver Charlesworth Avatar answered Oct 03 '22 18:10

Oliver Charlesworth


i = 0, ++i; 

As the other answer pointed out it is not Undefined Behaviour.

i = (0, ++i); 

The behaviour is undefined in this case because there is no sequence point between ++i and assignment to i.

i = (0, ++i, 0) 

The behaviour is well defined1 in C++03, IMHO.

1 See extended discussion for a similar expression.

like image 30
Prasoon Saurav Avatar answered Oct 03 '22 18:10

Prasoon Saurav