当前位置:网站首页>The pit of sizeof operator in C language

The pit of sizeof operator in C language

2022-07-04 23:33:00 InfoQ

Preface

When I was reading in my bedroom today , Asked by my roommate about
sizeof
The problem with the operator , Unexpectedly, he fell into the pit , It is hereby recorded that , So as not to “ Step into the same river again ”

Text

Let's start with a piece of code

#include <stdio.h>

int main()
{
 int i = 1;
 
 printf(&quot;%d\n&quot;,sizeof(i++));
 printf(&quot;%d\n&quot;,i);
 
 return 0;
}

What is the output of this code ?

First
sizeof
Is an operator used to calculate the memory size of a data type , stay VS in
int
Occupy 4 byte , So use
sizeof
After evaluation, it should be 4, And then we did
i++
, Then output i The value of should be 2.

So my answer is :

4
2

then … I was wrong and !(ÒωÓױ)

The correct answer should be :

4
1

Why is that ? Here's why :

Many beginners may think
sizeof
Is the function , Because its use is very similar to that of functions , It's not ,
sizeof
It's not a function , It's an operator
. If you check any one C When the operator priority table in Language Textbooks , We can all see the operator
sizeof
Is the highest priority
. Its usage is very simple , The result of solitude is the size of memory occupied by operands , When the operand can be
int
char
Data type , Or variables . But about
sizeof
Use with care , because
It completes the calculation at compile time , It is already a constant value when the function is running .

So
sizeof(i++)
Medium
i++
You can't calculate .╮(╯▽╰)╭
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042327181450.html