sizeof运算符用于返回其操作数的大小(以字节为单位)。此运算符始终在其操作数之前。操作数可以是数据类型或表达式。让我们通过适当的示例来看看这两个操作数。
- type-name :必须在括号中指定类型名称。
sizeof(type - name)
让我们看一下代码:
C
#include
int main() { printf("%lu\n", sizeof(char)); printf("%lu\n", sizeof(int)); printf("%lu\n", sizeof(float)); printf("%lu", sizeof(double)); return 0; }
C++
#include
using namespace std; int main() { cout << sizeof(char)<<"\n"; cout << sizeof(int)<<"\n"; cout << sizeof(float)<<"\n"; cout << sizeof(double)<<"\n"; return 0; }
C
#include
int main() { int i = 5; int int_size = sizeof(i++); // Displaying the size of the operand printf("\n size of i = %d", int_size); // Displaying the value of the operand printf("\n Value of i = %d", i); getchar(); return 0; }
C++
#include
using namespace std; int main() { int i = 5; int int_size = sizeof(i++); // Displaying the size of the operand cout << "\n size of i = " << int_size; // Displaying the value of the operand cout << "\n Value of i = " << i; return 0; } // This code is contributed by SHUBHAMSINGH10
输出:1 4 4 8
- expression :可以在带括号或不带括号的情况下指定表达式。
// First type sizeof expression // Second type sizeof(expression)
该表达式仅用于获取操作数的类型,而不用于求值。例如,下面的代码将i的值打印为5,并将ia的大小打印
C
#include
int main() { int i = 5; int int_size = sizeof(i++); // Displaying the size of the operand printf("\n size of i = %d", int_size); // Displaying the value of the operand printf("\n Value of i = %d", i); getchar(); return 0; } C++
#include
using namespace std; int main() { int i = 5; int int_size = sizeof(i++); // Displaying the size of the operand cout << "\n size of i = " << int_size; // Displaying the value of the operand cout << "\n Value of i = " << i; return 0; } // This code is contributed by SHUBHAMSINGH10 输出:size of i = 4 Value of i = 5
参考:
http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#The-sizeof-Operator
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。