2

Possible Duplicate:
Undefined Behavior and Sequence Points

Which 'C' compiler gives the logically correct answers... I mean Turbo C older version or the newer one named as Borland cpp 4.5 and above?

The different outputs of the question { int i=5;printf(i++*++i);} made me ask this.

Community
  • 1
  • 1
Nitish Pareek
  • 2,453
  • 3
  • 19
  • 18
  • That code shouldn't even compile. If it compiled, it would crash trying to access some memory adress around 30. And even if you fix that and use `printf("%d", i++*++i)`, ... well, that should be left to answers. –  Aug 29 '11 at 18:51
  • 9
    You asked the wrong question. Your question should be, "What do I need to do to stop myself writing nonsensical expressions like `i++*++i`?" – David Heffernan Aug 29 '11 at 18:54

1 Answers1

1

No C compiler will give a correct answer.

The most correct answer would be to detect nonsense of this kind and refuse to compile it with an error message.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
  • 3
    There is no "correct answer" here. The standard allows compilers to not error out, so failing to error out at compile time is exactly as 'correct' as doing something strange at runtime. – bdonlan Aug 29 '11 at 19:06
  • 1
    @bdonlan There is no correct answer, but there are tools that can tell you that the code is undoubtedly undefined, which is undoubtedly better than doing some random strange thing. Two such tools are http://code.google.com/p/c-semantics/ and http://frama-c.com/ – Pascal Cuoq Aug 29 '11 at 21:11
  • @Pascal, indeed, but in some cases that can have major performance implications. In this particular case, you could detect `a++ + a++`, but you can't really detect `(*a)++ + (*b)++` is undefined behavior, when the values of `a` and `b` are not known at compile time, without hurting performance – bdonlan Aug 29 '11 at 21:38
  • @bdonlan The two linked tools are interpreted and run at 1/100000th compiled speed (but both detect `(*a)++ + (*b)++` when `a` and `b` alias). The idea is to use them for testing/verification. It's possible to do faster, but even so, no-one said these were intended for deployment. There are just two more complementary testing tools for the conscientious C developer. – Pascal Cuoq Aug 29 '11 at 21:48