sizeof void或者函数

sizeof的标准规定:

https://en.cppreference.com/w/cpp/language/sizeof

sizeof cannot be used with function types, incomplete types, or bit-field glvalues.

When applied to a reference type, the result is the size of the referenced type.

When applied to a class type, the result is the size of an object of that class plus any additional padding required to place such object in an array.

The result of sizeof is always nonzero, even if applied to an empty class type.

但是,对于gcc来说:

http://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html

6.24 Arithmetic on void- and Function-Pointers

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.

A consequence of this is that sizeof is also allowed on void and on function types, and returns 1.

The option -Wpointer-arith requests a warning if these extensions are used.

因此,对于void和函数来说,其sizeof为1.

例子:

#include <stdio.h>

int test(int i)
{
    i++;
}

int main(void)
{
    int tmp_int = 1;
    int *int_ptr = &tmp_int;
    void *void_ptr = &tmp_int;

    printf("func name size is: %u\n", sizeof(test));

    printf("void size is: %u\n", sizeof(*void_ptr));

    printf("int ptr is [%p]\n", int_ptr);
    int_ptr++;
    printf("int ptr ++ is [%p]\n", int_ptr);

    printf("void ptr is [%p]\n", void_ptr);
    void_ptr++;
    printf("void ptr ++ is [%p]\n", void_ptr++);

    return 0;
}

输出:

func name size is: 1
void size is: 1
int ptr is [0x7fff97dec65c]
int ptr ++ is [0x7fff97dec660]
void ptr is [0x7fff97dec65c]
void ptr ++ is [0x7fff97dec65d]

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值