Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: 'cout << pointer << ++pointer' generates a compiler warning

I have a C++ learning demo here:

char c = 'M';
short s = 10;
long l = 1002;
char * cptr = &c;
short * sptr = &s;
long * lptr = &l;
cout << "cptr:\t" << static_cast<void*>(cptr) << '\n';
cout << "cptr++:\t" << static_cast<void*>(++cptr) << '\n';
cout << "sptr:\t" << sptr << '\n';
cout << "sptr++:\t" << ++sptr << '\n';
cout << "lptr:\t" << lptr << '\n';
cout << "lptr++:\t" << ++lptr << '\n';

cout << c << '\t' << static_cast<void*>(cptr) << '\t' << static_cast<void*>(++cptr) << '\n';
cout << s << '\t' << sptr << '\t' << ++sptr << '\n';
cout<< l << '\t' << lptr << '\t'<< ++lptr << '\n';

The compiler warnings:

image

Can anyone explain this to me? How to fix it?

like image 430
K.F Avatar asked Jul 27 '18 03:07

K.F


1 Answers

Since C++17 the code is correct.

Prior to C++17 the evaluation of operands of a << chain was unsequenced, so the code caused undefined behaviour.

The compiler warning suggests you are not compiling in C++17 mode. To fix it you could either:

  • Compile in C++17 mode, or
  • Separate the << chain into multiple cout << statements where there is not x and ++x within the same statement.

Note: As of now, all versions of g++ seem to be bugged and not implement these sequencing requirements correctly, see this thread for some more examples. The warnings can be seen as indicating the compiler bug; they are not just bogus warnings.

like image 180
M.M Avatar answered Oct 06 '22 01:10

M.M