【问题标题】:c++ strange std::cout behaviour using pointers [duplicate]c ++奇怪的std :: cout行为使用指针[重复]
【发布时间】:2023-05-31 20:33:01
【问题描述】:

可能重复:
What is the correct answer for cout << c++ << c;?

我刚输出文字,突然发现。

#include <iostream>
int main()
{    
 int array[] = {1,2,3,4};                 
 int *p = array;

    std::cout << *p << "___" << *(p++) << "\n";
    // output is  1__1. Strange, but I used  brackets! it should be at
    // first incremented, not clear.
    p = array;


   std::cout << *p << "___" << *(++p) << "\n";
   // output is 2_2   fine, why first number was affected? I didn't intend 
   // to increment it, but it was incremented
   p=array;


   std::cout << *p << "___" << *(p + 1) << "\n";
   // output is 1_2 - as it was expected
   p = array;

 return 0;
}

这样的行为对我来说很奇怪,为什么会这样?

【问题讨论】:

标签: c++ iostream cout


【解决方案1】:

你正在造成undefined behaviour,所以任何事情都可能发生,没有必要猜测原因。

表达式

std::cout<<*p<<"___"<<*(p++)<<"\n"

是一个例子:&lt;&lt; 之间所有事物的评估顺序是未指定的,因此 *p*(p++) 彼此之间是无序的(即不需要编译器先做任何一个) . You are not allowed to modify a variable and then use it without the modification and usage being sequenced,因此这会导致未定义的行为。

同样的事情适用于该程序中的所有其他地方,其中一个变量被修改并在同一表达式中单独使用。

【讨论】:

    最近更新 更多