【问题标题】:Why does this code have different outputs if pointers are incremented differently c++如果指针以不同的方式递增,为什么这段代码有不同的输出
【发布时间】:2021-12-29 09:22:13
【问题描述】:
#include <iostream>
using namespace std;
int main() {
  int num=10;
  int *ptr=NULL;
  ptr=&num;
  num=(*ptr)++; //it should increase to 11
  num=(*ptr)++; //it should increase to 12 but im getting 10
                //if i dont initialize num and just use (*ptr)++ it gives me 11
  cout<<num<<endl;
    return 0;
}

我想知道为什么会发生这种情况以及为什么我得到 10 作为输出。

【问题讨论】:

  • 又一个证据证明了为什么在一个表达式中改变一个值两次是不好的。 :-)
  • 请注意,在 C++17 之前num=(*ptr)++; 表现出未定义的行为。编译器可能不会发现它,但替换为 num = num++ 会生成 警告:使用 clang-cl 对 'num' [-Wunsequenced] 进行多次未排序的修改(使用 C++14 标准)。

标签: c++ pointers increment


【解决方案1】:

(*ptr)++num 增加到 11 但返回其先前的值 (10),因为 ++ 是后缀。

因此,对于num = (*ptr)++,您暂时将num 增加到11,但随后(重新)将其分配为10。

【讨论】:

  • 编码新手,不知道post fix这个词我会搜索一下谢谢回复
【解决方案2】:

为什么会这样

因为您使用的是后增量运算符而不是前增量运算符

(*ptr)++ 替换为:

num = ++(*ptr);//uses pre-increment operator

您将在程序结束时得到 12 作为输出,可以看到 here

替代解决方案

你也可以只写(*ptr)++;而不给num赋值。所以在这种情况下,代码看起来像:

int main() {
  int num=10;
  int *ptr=NULL;
  ptr=&num;
  (*ptr)++; //no need for assignment to num
  (*ptr)++; //no need for assignment to num
                
  cout<<num<<endl;
    return 0;
}

【讨论】:

  • 或者只是 (*ptr)++; 用于每个语句。
  • 我很新,不知道后期和预递增或递减会影响这样的代码,谢谢您的回复
  • @AliMardan 不客气。另请注意,正如 Adrian 建议的那样,您也可以使用 (*ptr)++; 而不分配num。我在答案的末尾添加了这个。看看吧。
【解决方案3】:

这是由于分配给num造成的。 ++ 运算符返回旧值,然后递增。但是,然后将旧值分配给 num。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 2021-02-16
    • 2019-07-17
    相关资源
    最近更新 更多