设为首页 加入收藏

TOP

5.8 The sizeof Operator
2013-10-07 15:24:27 来源: 作者: 【 】 浏览:71
Tags:5.8 The sizeof Operator

The sizeof operator returns a value of type size_t (Section 3.5.2, p. 104) that is the size, in bytes (Section 2.1, p. 35), of an object or type name. The result of sizeof expression is a compile-time constant. The sizeof operator takes one of the following forms:

  1. sizeof (type name);  
  2. sizeof (expr);  
  3. sizeof expr; 

Applying sizeof to an expr returns the size of the result type of that expression:

  1. Sales_item item, *p;  
  2. // three ways to obtain size required to hold an object of type Sales_item  
  3. sizeof(Sales_item); // size required to hold an object of type Sales_item  
  4. sizeof item; // size of item’s type, e.g., sizeof(Sales_item)  
  5. sizeof *p; // size of type to which p points, e.g., sizeof(Sales_item) 

eva luating sizeof expr does not eva luate the expression. In particular, in sizeof *p, the pointer p may hold an invalid address, because p is not dereferenced.

The result of applying sizeof depends in part on the type involved:

· sizeof char or an expression of type char is guaranteed to be 1

· sizeof a reference type returns the size of the memory necessary to contain an object of the referenced type

· sizeof a pointer returns the size needed hold a pointer; to obtain the size of the object to which the pointer points, the pointer must be dereferenced

· sizeof an array is equivalent to taking the sizeof the element type times the number of elements in the array

注意:sizeof 是操作符,不是函数。sizeof 表达式的值是在编译时确定的无符号整数,它只关心操作数的类型,而不会对操作数求值,izeof 当中的表达式的副作用也不会发生。

Because sizeof returns the size of the entire array, we can determine the number of elements by dividing the sizeof the array by the sizeof an element:

  1. // sizeof(ia)/sizeof(*ia) returns the number of elements in ia  
  2. int sz = sizeof(ia)/sizeof(*ia); 

根据本节的描述, 在C++(www.cppentry.com) 语言里一个char 就是一个byte,而一个byte 是8bits。这是符合普遍的实际情况的。

EXERCISES SECTION 5.8

Exercise 5.22: Write a programto print the size of each of the built-in types.

Exercise 5.23: Predict the output of the following program and explain your reasoning. Now run the program. Is the output what you expected If not, figure out why.

  1. int x[10]; int *p = x;  
  2. cout << sizeof(x)/sizeof(*x) << endl;  
  3. cout << sizeof(p)/sizeof(*p) << endl; 
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇5.12.6 Named Casts (1) 下一篇5.7 The Conditional Operator

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Sphinx : 高性能SQL (2025-12-24 10:18:11)
·Pandas 性能优化 - (2025-12-24 10:18:08)
·MySQL 索引 - 菜鸟教 (2025-12-24 10:18:06)
·Shell 基本运算符 - (2025-12-24 09:52:56)
·Shell 函数 | 菜鸟教 (2025-12-24 09:52:54)