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

后端 未结 3 1790
迷失自我
迷失自我 2021-01-18 02:37

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 <&         


        
3条回答
  •  天涯浪人
    2021-01-18 03:00

    According to C++ Standard Draft Paper N4762 (2018-07-07) on page 68 in section § 6.8.1/10

    ( or [intro.execution]/10 on eel.is website here )

    Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.


    For statement

    cout << c << '\t' << static_cast(cptr) << '\t' << static_cast(++cptr) << '\n';
    

    that means c++ compiler can not guarantee that static_cast(cptr) will be evaluated before ++cptr on the right because they are all operands on the same statement.

    So you can force their sequential order of execution simply by ordering them in ordered and separated statements.

    For example :

    cout << c << '\t' << static_cast(cptr) << '\t'; cout << static_cast(++cptr) << '\n';
    

    [ compiler explorer ]


    Update

    As M.M's answer states that c++17 now guarantees operand evaluation sequence of <<

    It turns out that GCC 8.1 doesn't warn, even with std=c++11, unless with -Wall and always warns with -Wall

    While clang 6.0 warns "no matter what".

    [ compiler explorer ]

    So, as well as -std=c++17, you must also provide option -Wno-unsequenced to suppress it :

    • if you are on clang 6.0
    • if you are on gcc 8.1 with -Wall

提交回复
热议问题