Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Keywords sizeof(), auto and typedef | Variables and Data Types
C++ Introduction
course content

Course Content

C++ Introduction

C++ Introduction

1. Getting Started
2. Variables and Data Types
3. Introduction to Operators
4. Introduction to Program Flow
5. Introduction to Functions

bookKeywords 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.

cpp

main

copy
12345678910
#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.

cpp

main

copy
1234567891011
#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.

cpp

main

copy
1234567891011121314
#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.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 6
some-alt