Chubsdad
Chubsdad

Reputation: 25497

Is this undefined behavior

From my understanding, this program should have undefined behavior.

#include <stdio.h>

int main()
{
   int a = 3, b = 3, c = 10, d = 20;
   int e = (a++ * ++b)-((c / b) * a) + d;
   printf("%d", e)  ;

   return 0;
}

The C99 standard §6.5 ¶2 says

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

So, in the line defining 'e', a and b are being read not only for determining what to store back in a and b, but also to compute the expression ((c / b) * a)

However, gcc does not give warning even with -Wsequence-point warning.

What am I missing here?

Upvotes: 4

Views: 145

Answers (1)

H.S.
H.S.

Reputation: 12669

When compiled with clang compiler (version - clang-1001.0.46.4), getting these warnings:

   p.c:6:19: warning: unsequenced modification and access to 'b' [-Wunsequenced]
       int e = (a++ * ++b)-((c / b) * a) + d;
                        ^        ~
   p.c:6:14: warning: unsequenced modification and access to 'a' [-Wunsequenced]
       int e = (a++ * ++b)-((c / b) * a) + d;
                ^                     ~

From C11 Standards#6.5p2 [emphasis added]

2 If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.84)

The expression invokes undefined behaviour.


Edit:

The question tagged with gcc, so for the completeness of answer below is the output when compiled with gcc compiler with -Wall option:

p.c:6:19: warning: operation on 'b' may be undefined [-Wsequence-point]
    int e = (a++ * ++b)-((c / b) * a) + d;
                   ^
p.c:6:14: warning: operation on 'a' may be undefined [-Wsequence-point]
    int e = (a++ * ++b)-((c / b) * a) + d;
              ^

Note that, if we do not specify any options (like -Wall or -Wsequence-point) to gcc while compiling, it's not giving any warning message on the expression in question but that's not the case with clang compiler.

Upvotes: 3

Related Questions