4

According to C++17, there is no guarantee for order of evaluation in following expression. It is called unspecified behaviour.

int i = 0;
std::cout<<i<<i++<<std::endl;

C++17 GCC compiler gives following warning: Live Demo

prog.cc: In function 'int main()':
prog.cc:6:20: warning: operation on 'i' may be undefined [-Wsequence-point]
     std::cout<<i<<i++<<std::endl;

I don't understand, in c++17 above express no longer undefined behaviour, then Why does compiler gives warning about undefined?

msc
  • 30,333
  • 19
  • 96
  • 184
  • It looks like it's giving a warning on the `i++` operation. https://www.ibm.com/support/knowledgecenter/en/SSB23S_1.1.0.14/common/m1rhoseq.html. `i + 1` does not give the warning – fredrik Dec 07 '17 at 13:51
  • Could you post a link to where the standard says it's unspecified and not undefined? – Kevin Dec 07 '17 at 13:51
  • @Kevin https://stackoverflow.com/questions/38501587/what-are-the-evaluation-order-guarantees-introduced-by-c17 – msc Dec 07 '17 at 13:57
  • It is not even unspecified, it is completely well-defined. – Matthijs Oct 28 '18 at 23:36

1 Answers1

5

Seems like gcc gives a warning because this is a corner case, or at least very close to being one. Portability seems to be one concern.

From the page https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

The C++17 standard will define the order of evaluation of operands in more cases: in particular it requires that the right-hand side of an assignment be evaluated before the left-hand side, so the above examples are no longer undefined. But this warning will still warn about them, to help people avoid writing code that is undefined in C and earlier revisions of C++.

The standard is worded confusingly, therefore there is some debate over the precise meaning of the sequence point rules in subtle cases. Links to discussions of the problem, including proposed formal definitions, may be found on the GCC readings page, at http://gcc.gnu.org/readings.html.

Community
  • 1
  • 1
Bo Persson
  • 86,087
  • 31
  • 138
  • 198
  • The second paragraph does not seem to be referring to the new C++17 rules, but rather to the old sequence point rules of C (and C++ prior to C++11). – Matthijs Oct 28 '18 at 23:34