1

Recently I faced an issue understanding the behaviour for printf() function.

This is what I was working with

#include<stdio.h>

int main(){
int a=5;
printf("%d %d %d",a++,a++,++a);
return 0;
}

When I ran this code snippet on gcc (linux) I got output as 7 6 8. But while running it on turbo (windows) I got output as 7 6 6.

What I understood is in turbo the parameters are passed in right to left order.

Can anyone explain how it works in linux using gcc.

sachy
  • 739
  • 7
  • 13
  • I suspect you are facing an undefined behavior – Felice Pollano Jun 04 '13 at 15:57
  • 2
    The order is implementation dependent, and you should not rely upon it. – Scott Jones Jun 04 '13 at 15:57
  • 2
    See [this](http://stackoverflow.com/questions/3812850/output-of-multiple-post-and-pre-increments-in-one-statement) also – Suvarna Pattayil Jun 04 '13 at 15:58
  • This is undefined behavior(UB) because you are modifying the value of `a` more than once without an intervening sequence point. Also, order of evaluation of function arguments is Unspecified so even if was not a UB, you wouldn't get a meaningful result. – Alok Save Jun 04 '13 at 15:59

2 Answers2

1

Your code contains several modifications of the same variable without any sequence points between the modifications. Thus, the code is incorrect, and results are unpredictable.

Also, order of evaluation of function parameters is implementation-defined.

nullptr
  • 11,008
  • 1
  • 23
  • 18
1

Different compilers may give different results in this situation. The question is not only about printf but also about parameter evaluation sequence.

What is an implementation defined behaviour?:

A language standard defines the semantics of the language constructs. When standard doesn't include the specifications of what to do in some case. Compiler designers may chose the path they think is correct. So, these constructs become implementation defined.

Since, that is not defined in standard, it's called undefined behaviour.

Unfortunately, these questions were given blindly given by many instructors in exams by merely testing in a compiler to set the question.

Example:

What is the output of following statement? But options don't include 
undefined behaviour

  #include<stdio.h>

    int main(){
    int a=5;
    printf("%d %d %d",a++,a++,++a);
    return 0;
    }
pinkpanther
  • 4,770
  • 2
  • 38
  • 62