朋友今天出了一道题
int main(void)
{
int i = 5;
printf("%d\n", sizeof(++i));
printf("%d\n", i);
return 0;
}
问i的值是多少,我想当然的问答是6。但实际运算结果是5,思考下第一反应应该是sizeof是编译时求值导致的。
先看下汇编结果:
.file "1.c"
.section .rodata
.LC0:
.string "%d\n"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movl $5, -4(%rbp)
movl $4, %esi --》》1
movl $.LC0, %edi
movl $0, %eax
call printf
movl -4(%rbp), %eax
movl %eax, %esi
movl $.LC0, %edi
movl $0, %eax
call printf
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (GNU) 4.8.5 20150623 (Red Hat 4.8.5-11)"
.section .note.GNU-stack,"",@progbits
看下标记1,实际上直接求出了i对应的数据类型值
这个应该是C标准规定的:
6.5.3.4 The sizeof operator
The sizeof operator yields the size (in bytes) of its operand, which may be an
expression or the parenthesized name of a type. The size is determined from the type of
the operand. The result is an integer. 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
其中明确说明了sizeof在非可变长度的数组情况下操作数是不会被求值的