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?
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With