sizeof 操作符

来源:互联网 发布:淘宝上东西质量怎么样 编辑:程序博客网 时间:2024/05/19 20:39

这是一个西山居的笔试题

一、sizeof属于C++内置函数?

不对,它应该属于一个操作符,在编译期间计算好的。
MSDN中这样描述:
The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types). This keyword returns a value of type size_t.

The expression is either an identifier or a type-cast expression (a type specifier enclosed in parentheses).

When applied to a structure type or variable, sizeof returns the actual size, which may include padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof returns the size of the entire array. The sizeof operator cannot return the size of dynamically allocated arrays or external arrays.

sizeof是C/C++中的一个操作符(operator),简单的说其作用就是返回一个对象或者类型所占的内存字节数。它返回一个size_t长度的单位是字节,sizeof表达式的结果是编译时常量,
sizeof可以对一个表达式求值,编译器根据表达式的最终结果类型来确定大小,一般不会对表达式进行计算,特别的当sizeof(*p)的时候,p可以是一个无效的地址,因为不需要对p做解引用的操作。
sizeof也可以对一个函数调用求值,其结果是函数返回类型的大小,函数并不会被调用。
sizeof的计算发生在编译时刻,所以它可以被当作常量表达式使用,如:char ary[ sizeof( int ) * 10 ];
sizeof数组的操作等效于对其元素做sizeof操作的结果城上数组元素的个数,所以用sizeof可以计算数组的元素个数,但是当一个数组做为一个函数的时候,数组名退化成一个指针,所以大多数的参数为数组时要传数组的大小,更多是起始和结束的下标符号。

 

原创粉丝点击