Checking size of variables by C

Every variable take some space in the memory. We can check size of variables using C++. Size of variables means the memory size we need to store them. Different variables need different space in the memory. In this C++ programming guide we will see C++ program to find the size of any variable.

C++ program to check the size of variables

We will use sizeof operator to print the size of any variable here. sizeof operator returns the size in byte for a variable. Now, let’s see the C++ program bellow.

// C++ program to find the size of variables

#include <iostream>
using namespace std;

int main(){

    cout <<"Size of character variable is " <<sizeof(char) <<" byte\n";

    cout <<"Size of integer variable is " <<sizeof(int) <<" bytes\n";

    cout <<"Size of long long integer variable is " <<sizeof(long long int) <<" bytes\n";

    cout <<"Size of float variable is " <<sizeof(float) <<" bytes\n";

    cout <<"Size of double variable is " <<sizeof(double) <<" bytes\n";

    cout <<"Size of long double variable is " <<sizeof(long double) <<" bytes\n";

    return 0;
}

Output of size of variables program

size-of-variables-in-c

You can also check the size using another method. The following program we have declared the variables first. Then we have checked the size of those variables without using their type. We have used only their name to determine the size of them.

// checking size of variable

#include <iostream>
using namespace std;

int main(){

    char a;
    short int b;
    int c;
    double d;
    long double e;

    cout <<"Size of variable a is " <<sizeof(a) <<" byte\n";

    cout <<"Size of variable b is " <<sizeof(b) <<" bytes\n";

    cout <<"Size of variable c is " <<sizeof(c) <<" bytes\n";

    cout <<"Size of variable d is " <<sizeof(d) <<" bytes\n";

    cout <<"Size of variable e is " <<sizeof(e) <<" bytes\n";

    return 0;
}

Output of this program: you will see the following output when you compile and run the above program.

Size of variable a is 1 byte
Size of variable b is 2 bytes
Size of variable c is 4 bytes
Size of variable d is 8 bytes
Size of variable e is 16 bytes

Previous pagePalindrome number

Next pageEven odd