John Humphreys
John Humphreys

Reputation: 39314

Undefined behavior in for loop - shouldn't the expression separation make this well-defined?

I know this topic has been beaten to death a little on SO, but I'm still a little confused about the situation shown below - and multiple people seemed to agree it was right.

I understand that you cannot modify/use a modified variable more than once without an intervening sequence point without it being undefined behavior. I thought that within a for loop though, the i != 0;, i < n; and i-- were all separate expressions, evaluated at known times, and separated by sequence points (as they are full expressions).

Why would this yield undefined behavior?

forum Image

taken from forum: http://www.frihost.com/forums/vt-48979.html

Upvotes: 1

Views: 584

Answers (3)

Lindydancer
Lindydancer

Reputation: 26134

The other answers commented on a different code than the one actually posted. The code was originally a puzzle, and one of the proposed solutions was to write the following:

for (i != 0; i < n; i--)

The problem with this is that it never assigns an initial value to i. Normally, this goes into the first part of the for-construct, but here is has been rewritten into (the totally pointless) i != 0. (It is pointless as it has no side effects and it's value is not used -- but, hey, this was a puzzle.)

Hence, this can run the loop an arbitrary number of times.

Upvotes: 1

ouah
ouah

Reputation: 145899

for (i = 0; i < n; i--)

This is code is undefined behavior if i is a signed integer AND if the i-- expression makes i overflows. (Actually in the C terminology only signed integers can overflow.)

Upvotes: 2

Alexandre C.
Alexandre C.

Reputation: 56976

For the original code of the post

for (i = 0; i < n; i--)

the code is undefined because of the way signed integer arithmetic works. There is no guarantee that i will ever wrap around and become positive. With unsigned arithmetic, the code becomes defined (but the behavior is unspecified, because the size of an unsigned int is unspecified).

As for the line corresponding to your screenshot, the variable i is never initialized, hence the undefined behavior.

Upvotes: 6

Related Questions