为什么 n++ 在作为 sizeof() 函数的参数时不起作用?
Why n++ not work when it is an argument for sizeof() function?
int main() {
int n = 1;
sizeof(n++);
printf("%d",n);
return 0;
}
这是我的代码的一部分。输出是1。但是为什么n
没有增加1呢?
我尝试了其他功能,但其他功能的输出是 2.
因为sizeof
不是函数,而是运算符。它的参数没有副作用。
这是因为,sizeof
不是一个函数,它是一个编译时运算符,除非操作数是 VLA,否则操作数不会在运行时求值。
引用 C11
,章节 §6.5.3.4
[...] If the type of the operand is a variable length array
type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an
integer constant.
补充一点为什么它不需要计算操作数,从操作数的语义来看,
[....] The size is determined from the type of
the operand. [...]
而且,操作数的类型是固定的,并且在编译时已知(除非是 VLA),因此它不需要评估操作数来执行它的工作。在你的例子中,因为 n
是 int
类型
sizeof (n++);
和
一样
sizeof (int);
sizeof
不是一个函数,它是一个运算符。
sizeof(n++)
等同于 sizeof n++
,后者(因为 n
是一个 int
)等同于 sizeof (int)
.
sizeof
只看其操作数的类型;它不计算表达式。
(除非涉及变长数组,但我们暂时忽略它。)
int main() {
int n = 1;
sizeof(n++);
printf("%d",n);
return 0;
}
这是我的代码的一部分。输出是1。但是为什么n
没有增加1呢?
我尝试了其他功能,但其他功能的输出是 2.
因为sizeof
不是函数,而是运算符。它的参数没有副作用。
这是因为,sizeof
不是一个函数,它是一个编译时运算符,除非操作数是 VLA,否则操作数不会在运行时求值。
引用 C11
,章节 §6.5.3.4
[...] If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.
补充一点为什么它不需要计算操作数,从操作数的语义来看,
[....] The size is determined from the type of the operand. [...]
而且,操作数的类型是固定的,并且在编译时已知(除非是 VLA),因此它不需要评估操作数来执行它的工作。在你的例子中,因为 n
是 int
sizeof (n++);
和
一样 sizeof (int);
sizeof
不是一个函数,它是一个运算符。
sizeof(n++)
等同于 sizeof n++
,后者(因为 n
是一个 int
)等同于 sizeof (int)
.
sizeof
只看其操作数的类型;它不计算表达式。
(除非涉及变长数组,但我们暂时忽略它。)