被++一样+ = 1的指针? [英] Is ++ the same as += 1 for pointers?

查看:150
本文介绍了被++一样+ = 1的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重构我的一些旧的C code,我很好奇,如果我可以取代所有 PTR ++ PTR + = 1 ,其中 PTR 是一些指针,不改变任何行为。下面是我的意思,从K&放一个例子; R第5.3节:

I'd like to refactor some old C code of mine, and I was curious if I can replace all ptr++ with ptr += 1 where ptris some pointer, without changing any behavior. Here's an example of what I mean, from K&R Section 5.3:

/* strlen: return length of string s*/
int strlen(char *s)
{
    int n;
    for (n = 0; *s != '\0'; s++)
        n++;
    return n;
}

当我与 S + = 1 替换取值++ ,我得到相同的结果,但我想知道这将是对所有类型的情况。我还做了一个测试为 INT 取值:

When I replace the s++ with s += 1, I get the same results, but I'm wondering if this will be the case for all types. I also did a test for ints:

int size = 10;
int *int_array = (int*)calloc(size, sizeof(int));
for (int i = 0; i < size; i++)
    int_array[i] = i;

for (int i = 0; i < size; i++) {
    printf("*int_array = %d\n", i, *int_array);
    int_array++;
}

如果我更换行 INT_ARRAY ++; INT_ARRAY + = 1; ,我得到相同的结果

If I replace the line int_array++; with int_array += 1;, I get the same result.

在思考这个多一些之后,我意识到,如果该值在一个前pression使用有可能是一个问题。难道是我安全刚搬到增量到像这样另一行:

After thinking about this some more, I realize there could be a problem if the value is used in an expression. Would it be safer I just moved the increment onto another line like so:

int a = 5;
int b = a++;

将变成:

int a = 5;
int b = a;
a += 1;

结论

我认为可能是一个问题,递增的不同类型的指针,是没有问题的。见@ bdonlan的为什么的原因响应。

What I thought could be a problem, incrementing pointers of different types, is not a problem. See @bdonlan's response for the reason why.

这并不意味着你可以替换所有 X ++ X + = 1 ,并期望相同的行为。你可以,但是,替换 ++ X (X + = 1)安全,因为它们是等价的。

This doesn't mean that you can replace all x++ with x += 1 and expect the same behavior. You can, however, replace ++x with (x += 1) safely, since they are equivalent.

推荐答案

A + = 1 等同于 ++中的(C99§6.5.3.1/ 2)。在像 INT B A线= A ++; 这意味着它的的等同于 A ++ ; A ++ 将返回的 A ,而的价值+ = 1 返回新的值。

a += 1 is equivalent to ++a (C99 §6.5.3.1/2). In a line like int b = a++; this means it is not equivalent to a++; a++ would return the old value of a, while a += 1 returns the new value.

请注意,如果你不使用 A ++的结果(也就是说,你有一个包含一份声明中只是 A ++; ),那么它们实际上是相同的。

Note that if you don't use the result of a++ (ie, you have a statement containing just a++;), then they are effectively identical.

另外,还要注意_all指针运算中所指向的类型的大小(§6.5.6/ 8)为单位进行。这意味着:

Also, note that _all pointer arithmetic is done in increments of the pointed-to type's size (§6.5.6/8). This means that:

ptr = ptr + x;

相当于:

ptr = (ptr_type *)( (char *)ptr + x * sizeof(*ptr) );

这是你是否使用相同的 + ++ + = [] p [X] 完全等同于 *(p + X);你甚至可以做这样的事情 4你好] )

This is the same whether you use +, ++, +=, or [] (p[x] is exactly equivalent to *(p + x); you can even do things like 4["Hello"] because of this).

这篇关于被++一样+ = 1的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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