简体   繁体   English

C中的后增量运算符

[英]Post-increment operator in C

I was casually coding when I wrote this C code: 我编写这个C代码时,我随便编码:

#include <stdio.h>
int main()
{
    int i;
    i = 10;
    printf("i : %d\n",i);
    printf("sizeof(i++) is: %d\n",sizeof(i++));
    printf("i : %d\n",i);
    return 0;
}

And when I ran the code, the result I get is, 当我运行代码时,我得到的结果是,

i : 10
sizeof(i++) is: 4
i : 10

I was baffled by this result as I expected i++ inside sizeof operator to have incremented i. 我对这个结果感到困惑,因为我预计i ++内的sizeof运算符会增加i。 But it seems not. 但似乎没有。 So out of curiosity I wrote the following program: 因此,出于好奇,我写了以下程序:

#include <stdio.h>
int  add(int i)
{
    int a = i + 2;
    return 4;
}
int main()
{
    int i;
    i = 10;
    printf("i : %d\n",i);
    printf("sizeof(i++) is: %d\n",add(i++));
    printf("i : %d\n",i);
    return 0;
}

for this program, the output is: 对于这个程序,输出是:

i : 10
sizeof(i++) is: 4
i : 11

Now I'm more and more baffled. 现在我越来越困惑了。

Sorry if this is a noob question (which I am) but I don't really understand even how to google for such a problem! 对不起,如果这是一个noob问题(我是)但我真的不明白甚至如何谷歌这样的问题!

Why is the value of i different in these two programs? 为什么这两个程序中i的值不同? Please help! 请帮忙!

sizeof() isn't a runtime function. sizeof()不是运行时函数。 It just gives you the size of the variable or the size of the return value of a function. 它只是给出变量的大小或函数返回值的大小。

So in the first example, you're just getting the size of the result value of a post-increment operator on an integer which is an integer... 4 bytes. 所以在第一个例子中,你只是将一个后增量运算符的结果值的大小放在一个整数... 4个字节的整数上。

In your example you're just printing the return value of your method which returns 4, and then the variable increments, and you print 11. 在您的示例中,您只是打印返回4的方法的返回值,然后变量递增,并打印11。

sizeof does not evaluate its operand (except in VLA-type situations). sizeof不评估其操作数(VLA类型情况除外)。

That means that sizeof(*(T*)(NULL)) is the same as sizeof(T) , and perfectly validly so. 这意味着sizeof(*(T*)(NULL))sizeof(T)相同,完全有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM