sizeof运算符用于返回其操作数的大小(以字节为单位)。此运算符始终位于其操作数之前。操作数可以是数据类型,也可以是表达式。让我们通过适当的例子来看看这两个操作数。
null
- 类型名 :必须在括号中指定类型名称。
sizeof
(type - name)
让我们看看代码:
C
#include <stdio.h>
int
main()
{
printf
(
"%lu"
,
sizeof
(
char
));
printf
(
"%lu"
,
sizeof
(
int
));
printf
(
"%lu"
,
sizeof
(
float
));
printf
(
"%lu"
,
sizeof
(
double
));
return
0;
}
C++
#include <iostream>
using
namespace
std;
int
main()
{
cout <<
sizeof
(
char
)<<
""
;
cout <<
sizeof
(
int
)<<
""
;
cout <<
sizeof
(
float
)<<
""
;
cout <<
sizeof
(
double
)<<
""
;
return
0;
}
输出:1 4 4 8
- 表示 :表达式可以使用括号指定,也可以不使用括号指定。
// First type
sizeof
expression
// Second type
sizeof
(expression)
表达式仅用于获取操作数类型,不用于计算。例如,下面的代码将i的值打印为5,并将i的大小打印为a
C
#include <stdio.h>
int
main()
{
int
i = 5;
int
int_size =
sizeof
(i++);
// Displaying the size of the operand
printf
(
" size of i = %d"
, int_size);
// Displaying the value of the operand
printf
(
" Value of i = %d"
, i);
getchar
();
return
0;
}
C++
#include <iostream>
using
namespace
std;
int
main()
{
int
i = 5;
int
int_size =
sizeof
(i++);
// Displaying the size of the operand
cout <<
" size of i = "
<< int_size;
// Displaying the value of the operand
cout <<
" 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运算符
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END