What is the return type of sizeof operator?

C++Visual Studio-2010Sizeof

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

size_t is an alias of some implementation-defined unsigned integral type. In C++ opposite to C where sizeof operator may be applied to VLA arrays the operand of sizeof operator is not evaluated (at run time). It is a constant. If the value of sizeof operator can be fit into int type the compiler does not issue a warning. In the second example std::strlen is evaluated at run time so its result can do not fit into int so the compiler issues a warning. You could substitute std:;strlen with your own constexpr function (some recursive function). In this case if the result can fit into int I think that the compiler will not issue a warning.

Solution 3 - C++

The sizeof operator is used to get the size of types or variable in bytes. Returns an unsigned integer type of at least 16 bit. It's used to get portability.

This warning is because of the unsigned integer where is defined the size_t.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCoder777View Question on Stackoverflow
Solution 1 - C++Matteo ItaliaView Answer on Stackoverflow
Solution 2 - C++Vlad from MoscowView Answer on Stackoverflow
Solution 3 - C++dpossamaiView Answer on Stackoverflow