The easiest way to define a C program

Consider program C below:

#include <stdio.h> int f() { printf("f"); return 1; } int g() { printf("g"); return 2; } int main() { return f() + g(); } 

According to the C standard, this program does not have one deterministic behavior due to the sum in the main function, which consists of two subexpressions and the following excerpt from the C99 standard:

§6.5 (...) the procedure for evaluating subexpressions and the order in which side effects occur are not specified.

Therefore, printing fg and gf are valid outputs for this program. In practice, this compiler will choose one fixed evaluation order (for example, from left to right for gcc in this case), but if I want to reliably compare the result between different compilers, I need to make sure that my program has one specific behavior.

My question is: what is the easiest way to do this? Is there a way to avoid including temporary variables (e.g. int tmp = f(); return tmp + g(); )?

+4
source share
3 answers

To ensure the order of evaluation, you need to have a sequence point between function calls.

The easiest way is to use a local variable to store the intermediate result.

This will rarely be a problem unless you have deep recursion or extremely tight memory limits.

+1
source

The answer is straightforward and simple: avoid vague behavior.

In the case of your example, if the return value of main does not matter, you can use this:

 return f(), g(); 

The comma operator can verify that the operands are executed from left to right.

If you need the value f() + g() , you need to use a temporary variable.

+2
source

Not from the Standard; the easiest way is to use a temporary variable.

+1
source

Source: https://habr.com/ru/post/1498398/


All Articles