Home > Software engineering >  Sequence point, function call and undefined behaviour
Sequence point, function call and undefined behaviour

Time:09-30

main.cpp

const int& f(int& i ) { return (  i);}
int main(){   
    int i = 10;
    int a = i     i  ; //undefined behavior
    int b = f(i)   f(i); //but this is not
}

compile

$ g   main.cpp -Wsequence-point

statement int a = i i ; is undefined behaviour.

statement int b = f(i) f(i); is not undefined . why?

CodePudding user response:

statement int b = f(i) f(i); is not undefined . why?

No, the second statement will result in unspecified behavior. You can confirm this here. As you'll see in the above linked demo, gcc gives the output as 23 while msvc gives 24 for the same program.

CodePudding user response:

Pre-c 11, we use Sequence_point_rules:

Pre-C 11 Undefined behavior

  1. Between the previous and next sequence point, the value of any object in a memory location must be modified at most once by the evaluation of an expression, otherwise the behavior is undefined.

Pre-C 11 Rules 3) There is a sequence point after the copying of a returned value of a function and before the execution of any expressions outside the function.

  • In int a = i i ;, i is modified twice
  • In int b = f(i) f(i);, there are sequence point with function call. i is modified only once between the sequence call. so no UB.
    Note though that order of evaluation is unspecified so (evaluation of result) f(i) might happens after or before the second f(i), which might lead to different result depending of optimization/compiler and even between call.

Since C 11, we use "Sequenced before" rules, which is a similar way disallows i i but allows f(i) f(i).

  •  Tags:  
  • c
  • Related