Course Content
C++ Introduction
C++ Introduction
Keywords sizeof(), auto and typedef
The size of a variable is the amount of memory reserved by the compiler. The compiler reserves a specific number of bytes from your computer's memory, based on the data type you are using. You can use the sizeof()
function to find out the size of a variable or data type in bytes.
main
#include <iostream> int main() { int myVar1; char myVar2; std::cout << "Size of int: " << sizeof(myVar1) << std::endl; std::cout << "Size of char: " << sizeof(myVar2) << std::endl; }
C++ allows you to select a type with a precise bit size, such as int8_t
, uint8_t
, int16_t
,uint16_t
, etc. To use these data types, you will need to include the <cstdint>
header file.
Additionally, we can force the compiler to determine the variable type on its own using the auto
keyword.
main
#include <iostream> int main() { auto myVar = 64.565; std::cout << "Value of myVar : " << myVar << std::endl; // double type takes 8 bytes std::cout << "Size of myVar : " << sizeof(myVar) << std::endl; }
C++ also allows you to rename existing data types for yourself. This is what typedef
is used for.
main
#include <iostream> int main() { //change name of double type to MY_NEW_TYPE typedef double MY_NEW_TYPE; MY_NEW_TYPE myVar = 64.565; std::cout << "Value of myVar: " << myVar << std::endl; // double type takes 8 bytes std::cout << "Size of myVar : " << sizeof(myVar) << std::endl; }
When compiled, the typedef
line tells the compiler that MY_NEW_TYPE
is just a double
type.
Thanks for your feedback!