Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size in bytes for literals

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?

like image 906
jacksonSD Avatar asked Nov 24 '25 23:11

jacksonSD


2 Answers

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;
}   
like image 156
jjaguayo Avatar answered Nov 26 '25 16:11

jjaguayo


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
like image 20
Shafik Yaghmour Avatar answered Nov 26 '25 16:11

Shafik Yaghmour