0

I am unable to findout the problem with the code below. I get warning message "operation on 'ptr' may be undefined" on printf statement. Also the the result is printed in reverse order (7 is printed aganst Element1 and 2 against element2)

int main()
{
    int a[4] = {2,7,9,0};
    int *ptr=a;
    printf("Element1 = %d Element 2 = %d", *ptr, *ptr++);
    ptr++;
    return 0;
}
Jon Wheelock
  • 263
  • 3
  • 16

2 Answers2

4

The C standard does not define in what order the parameters get evaluated. Try using *(ptr+1) instead of *ptr++, which also can be replaced with ptr[1].

PineForestRanch
  • 473
  • 2
  • 11
  • Nor does it define when the increment occurs beyond 'before the actual call to `printf()` occurs'. – Jonathan Leffler Oct 11 '15 at 16:49
  • @JonathanLeffler and most implementations evaluate the parameters form right to left, no? – A.S.H Oct 11 '15 at 17:09
  • 1
    @A.S.H: I don't know which order implementations evaluate their arguments; I've never bothered to investigate since the behaviour can change from system to system, compiler to compiler, version to version, or even at the whim of the compiler during a single compilation. It isn't useful information to me — I'd suggest you're better off not knowing as well, and ensuring that your code works correctly regardless of which order the compiler chooses. – Jonathan Leffler Oct 11 '15 at 17:14
  • @JonathanLeffler I agree with you, it's only that i remembered the days when we studied how C pushed the parameters in reverse order, and that was a design choice precisely to permit the implementation of printf. But you are right, better not know and not count on it. – A.S.H Oct 11 '15 at 17:19
  • Just curious: Why latest C compilers does not take care of such issues? Why C has lot of undefined behavior (or so called features) which may add more bugs to the code? Do we have any good C compilers that take care of all such issues? – Jon Wheelock Oct 12 '15 at 01:42
  • I believe this gives compilers a freedom to optimize their behaviour. It would be hard to formalize except for simplest cases anyway, and consequently hard to remember for the programmer. – PineForestRanch Oct 12 '15 at 02:36
2

There's no sequenceing or specified evaluation order for function arguments so you don't know which argument will be evaluated first, *ptr or *ptr++ (or even the string literal), which leads to undefined behavior.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621