Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is (c++)*(c++) undefined behavior in C++? [duplicate]

Tags:

c++

I am confused about the output of this code:

int c=3;
cout<<(c++)*(c++);

I use gcc and the output is 9, but someone said that it's undefined behavior, why?

like image 797
StackBox Avatar asked Feb 21 '23 16:02

StackBox


1 Answers

The issue is "Sequence points":

http://en.wikipedia.org/wiki/Sequence_point

A sequence point in imperative programming defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed.

Sequence points also come into play when the same variable is modified more than once within a single expression. An often-cited example is the C expression i=i++, which apparently both assigns i its previous value and increments i. The final value of i is ambiguous, because, depending on the order of expression evaluation, the increment may occur before, after, or interleaved with the assignment. The definition of a particular language might specify one of the possible behaviors or simply say the behavior is undefined. In C and C++, evaluating such an expression yields undefined behavior.[1]

As it happens, I get exactly the same answer - "9" - on both MSVC (Windows) and gcc (Linux). I also get a warning whether I compile with gcc ("C") or g++ (C++):

$ g++ -o tmp -Wall -pedantic tmp.cpp
tmp.cpp: In function "main(int, char**)":
tmp.cpp:7: warning: operation on "c" may be undefined
$ ./tmp
c=9...
like image 78
paulsm4 Avatar answered Mar 06 '23 00:03

paulsm4