Live data from Hacker News

A glimpse of undefined behavior in C

blog.chris-cole.net

11–20 of 67 posts

Re: A glimpse of undefined behavior in C

#11
post #8

Earlier quoted context omitted.

This is incorrect; it is undefined behavior according to the spec: http://www.reddit.com/r/programming/comments/1rrefp/a_glimps...

Ok, so do any other compilers handle it differently?

Exactly. De facto defined is usually just as important to consider as de jure.

Re: A glimpse of undefined behavior in C

#12
post #5

Not "well-defined" is the proper terminology.

What is the difference? I do not see "well-defined" in the "Terms, definitions, and symbols" part of the standard.

It is 'de facto' defined.

http://en.wikipedia.org/wiki/De_facto

:)

Re: A glimpse of undefined behavior in C

#13
post #8

Earlier quoted context omitted.

This is incorrect; it is undefined behavior according to the spec: http://www.reddit.com/r/programming/comments/1rrefp/a_glimps...

Ok, so do any other compilers handle it differently?

Practically every new version of gcc adds a new optimization that recognizes some new form of undefined behavior and then rewrites your function to do whatever it wants.

Classic example: signed integer overflow. It worked for decades. Then one day it didn't.

If you want to know about this particular example: https://news.ycombinator.com/item?id=6824514 (not personally confirmed)

Re: A glimpse of undefined behavior in C

#14
post #8

Earlier quoted context omitted.

This is incorrect; it is undefined behavior according to the spec: http://www.reddit.com/r/programming/comments/1rrefp/a_glimps...

Ok, so do any other compilers handle it differently?

Yep.

Clang says:

  zsh% clang -o sequencepoints sequencepoints.c
  sequencepoints.c:7:18: warning: multiple unsequenced modifications to 'i' [-Wunsequenced]
    int r = 1 * a[i++] + 2 * a[i++] + 3 * a[i++];
                   ^            ~~
  1 warning generated.
And prints:

  zsh% ./sequencepoints
  140

Re: A glimpse of undefined behavior in C

#18
post #5

Earlier quoted context omitted.

What is the difference? I do not see "well-defined" in the "Terms, definitions, and symbols" part of the standard.

It is 'de facto' defined. http://en.wikipedia.org/wiki/De_facto :)

"de facto" defined means nothing. Compilers change and break programs that depend on undefined behavior all the time.

Re: A glimpse of undefined behavior in C

#19

The way I learned that in C a long time ago was "post increment" was "post statement increment".

it's a little weirder though. int main(int argc, char argv) { int a = 0; printf("%i %i %i\n", a, a++, a++); }

will give "0 0 1" (gcc 4.2.1), the increment "shouldn't" happen until after the ; if you're going with post statement. I think your rule would expect "0 0 0" with a being 2 after the printf.

BUT! you get a warning, so that's nice.

Post reply on HN