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

  • A+
Category:Languages

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:

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

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

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: