gpt4 book ai didi

C++: 'cout << pointer <<++pointer' 生成编译器警告

转载 作者:可可西里 更新时间:2023-11-01 18:23:40 25 4
gpt4 key购买 nike

我这里有一个C++学习demo:

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';

编译器警告:

image

谁能给我解释一下?如何解决?

最佳答案

Since C++17 the code is correct .

Prior to C++17 << 的操作数评估链是未排序的,因此代码导致了未定义的行为。

编译器警告表明您没有在 C++17 模式下编译。要修复它,您可以:

  • 在 C++17 模式下编译,或者
  • << 分开链成多个cout <<没有 x 的语句和 ++x在同一声明中。

注意:截至目前,所有版本的 g++ 似乎都存在错误并且无法正确实现这些排序要求,请参阅 this thread有关更多示例。可以将警告视为指示编译器错误;它们不仅仅是虚假警告。

关于C++: 'cout << pointer <<++pointer' 生成编译器警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51550156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com