多个“++”变量工作和指针 [英] multiple '++' working in variables, and pointers

查看:105
本文介绍了多个“++”变量工作和指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我认为的 ++ 运营商确实

This is what I think the ++ operator does


  1. A ++; // A + = 1计算该行后

  2. ++一个; // A + = 1 calcuating此行之前

  1. a++; // a+=1 after calculating this line
  2. ++a; // a+=1 before calcuating this line

我想学习指针,我认为我误解的东西。

I'm trying to study pointers, and I think that I misunderstood something.

int a=10;
int arr[3]={0,1,2};
int *ptr;
ptr=arr;

printf("%d,%d,%d,%d\n",a++,a++,++a,++a);
printf("%d,%d,%d\n", ptr[0],ptr[1],ptr[2]);
printf("%d,%d,%d,%d,%d,%d", * ptr++, ( * ptr)++, ++ * ptr, ++( * ptr), *++ptr, * ptr);

我期望的输出是:

I expected that the output to be:

12, 12, 12, 12
0,1,2
3,3,3,3,3,3,3

但事实并非如此。它是这样的:

But it wasn't. It was this:

13,12,14,14
0,1,2
4,3,2,2,2,2

这是为什么?

推荐答案

你不应该做的争论不止一个增量功能..因为他们可以在评估顺序是模糊的。例如code的结果是不确定的。

You're not supposed to do more than one increment in arguments to a function.. because the order they can be evaluated in is ambiguous. The result of such code is undefined.

含义:的printf(%D,%D,%D,%d个\\ N,一++中,++,++中,++一); 应该写为

a++; a++;
++a; ++a;
printf("%d, %d, %d, %d\n", a, a, a, a);

尝试修复首先,看看结果依然扑朔迷离。

Try and fix that first and see if the results are still confusing.

更一般地,你应该只拥有一双序列点之间的一个增量。

More generally, you should only have one increment between a pair of sequence points.

编辑:的克里斯是正确的,没有一点写作的无处中间的四个增量。为了更好地回答你的问题:对于一个函数无效F(INT)无效克(INT) int类型的= 0

Chris is right, there's no point writing four increments in the middle of nowhere. To better answer your question: For a function void f(int) and void g(int), with int a=0,

f(++a) = f(1);
f(a++) = f(0);
g(++a, ++a) = g(???); // undefined!

所以,在函数参数增加最多一次。

So, increment at most once in the argument to a function.

这篇关于多个“++”变量工作和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆