sizeof(i++)

朋友今天出了一道题

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在非可变长度的数组情况下操作数是不会被求值的


  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值