In this example, you will learn how to find the size of a variable and display the results.
Contents
You can learn more C Programming concepts here.
Program to find the size of a variable
#include<stdio.h>
int main() {
int integer;
long longType;
float floatType;
double doubleType;
char charType;
// sizeof evaluates the size of a variable
printf("Size of int is %zu bytes\n", sizeof(integer));
printf("Size of long is %zu bytes\n", sizeof(longType));
printf("Size of float is %zu bytes\n", sizeof(floatType));
printf("Size of double is %zu bytes\n", sizeof(doubleType));
printf("Size of char is %zu byte\n", sizeof(charType));
return 0;
}
Run Code on Online C CompilerOutput
Size of int is 4 bytes
Size of long is 8 bytes
Size of float is 4 bytes
Size of double is 8 bytes
Size of char is 1 byte
Explanation
The sizeof is an operator which returns the size of a variable. The output of sizeof may vary on the 32-bit machines and 64-bit machines for the same variable.
This C program declares five variables of different data types: integer
of type int
, longType
of type long
, floatType
of type float
, doubleType
of type double
, and charType
of type char
.
Then, the program uses the sizeof()
function to determine the size (in bytes) of each of these variables and prints the results using printf()
.
The %zu
format specifier is used to print the result of the sizeof()
function, which returns a value of type size_t
. This specifier tells printf()
to expect an argument of type size_t
.
Finally, the program returns 0, indicating successful completion of the main()
function.
Overall, this program is a simple example of how to use the sizeof()
function to determine the size of variables in C.