sizeof运算符的返回类型是什么? [英] What is the return type of sizeof operator?

查看:959
本文介绍了sizeof运算符的返回类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sizeof运算符的返回类型是什么? cppreference.com& msdn说sizeof返回size_t。它真的返回一个size_t吗?
我使用VS2010专业版,并针对x64。

What is the return type of sizeof operator? cppreference.com & msdn says sizeof returns size_t. Does it really return a size_t? I'm using VS2010 Professional, and targeting for x64.

int main()
{
    int size   = sizeof(int);     // No warning
    int length = strlen("Expo");  //warning C4267: 'initializing' : conversion from 'size_t' to 'int', possible loss of data
    return 0;
}

我有这个问题,因为第一行没有发出任何警告,是的。即使我将其更改为char大小,也不会收到任何警告。

I have this question because first line is not issuing any warning, whereas the second does. Even if I change it to char size, I don't get any warnings.

推荐答案

C ++ 11,§5.3。 3¶6

C++11, §5.3.3 ¶6


sizeof ... std :: size_t 类型的常量。 [注:std :: size_t在
中定义为标准头(18.2)。 - end note]

The result of sizeof and sizeof... is a constant of type std::size_t. [ Note: std::size_t is defined in the standard header (18.2). — end note ]

您也可以快速检查:

#include <iostream>
#include <typeinfo>
#include <cstdlib>

int main()
{
    std::cout<<(typeid(sizeof(int))==typeid(std::size_t))<<std::endl;
    return 0;
}

正确输出 1 在我的机器上。

which correctly outputs 1 on my machine.

作为 @Adam D. Ruppe 在注释中说,可能编译器不抱怨,结果,它知道这种转换是不危险的

As @Adam D. Ruppe said in the comment, probably the compiler does not complain because, since it already knows the result, it knows that such "conversion" is not dangerous

这篇关于sizeof运算符的返回类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆