Question

What is the size (in bytes) for each of the literals '7', 7.0, “7”?

I was tasked with this question and to be honest, I have no idea how to find the size of these in bytes. Can someone point me in the right direction?

Was it helpful?

Solution

One approach is to use the sizeof operator.

for example,

#include <iostream>
#include <math.h>

int main(int argc, char **argv)
{
    std::cout << "size of char 6 is " << sizeof('6') << std::endl;
    std::cout << "size of float 6.0 is " << sizeof(6.0) << std::endl;
    std::cout << "size of string 6 is " << sizeof("6") << std::endl;

    return 0;
}   

OTHER TIPS

In the interest of teaching you how to fish as opposed to giving you a fish, let's break this down into two parts. First how do we find the types of these literals, typeid is perfect for this problem:

#include <typeinfo>
#include <iostream>

int main()
{
    std::cout << typeid( '7' ).name() << std::endl ;
    std::cout << typeid( 7.0 ).name() << std::endl ;
    std::cout << typeid( "7" ).name() << std::endl ;
}  

We are using clang and so the output is as follows (see it live):

c
d
A2_c

In Visual Studio you will get the types directly (see it live)

If we had to demangle we would using c++filt -t and we see:

char
double
char [2]

Now we know out types we can find their sizes using sizeof:

#include <typeinfo>
#include <iostream>

int main()
{
    std::cout << sizeof( char)  << std::endl ;
    std::cout << sizeof( double )  << std::endl ;
    std::cout << sizeof( char [2] ) << std::endl ;
}   

for me the result is:

1
8
2

To be pedantic, in general case literals themselves do not have physical size. It makes little sense to apply the notion of "size in bytes" to something that is not "material", i.e. does not reside in memory. The only exception here is string literal "7", which is an lvalue. Meanwhile, '7' and 7.0 are not lvalues.

Anyway, when you apply sizeof to a literal value (if that's what you meant by "size in bytes"), the literal is interpreted as a simple expression. And what you get is size of the type that expression has. So, '7' has type char and size 1, 7.0 has type double and size sizeof(double) (implementation dependent), "7" has type const char[2] and size 2.

(Note that array-to-pointer conversion is not applied to the immediate operand of sizeof, which is why sizeof "7" evaluates to array size, not to pointer size.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top