Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

c++ - What is the return type of sizeof operator?

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;
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

C++11, §5.3.3 ?6

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 ]

You can also do a quick check:

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

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

which correctly outputs 1 on my machine.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...