sizeof() – Sizeof operator in C/C++

sizeof() – Sizeof operator in C/C++

sizeof(type/variable/expression)

sizeof() operator is a unary operator. It is used to determine the size of a variable, expression or data type. It returns the memory allocated to them in number of bytes.

Let’s see a program to understand the use of sizeof():

Program in C :

#include<stdio.h>
int main() {
  printf( "\n Size of char datatype = %d", sizeof(char));
  printf( "\n Size of int datatype = %d", sizeof(int));
  printf( "\n Size of float datatype = %d", sizeof(float));
  printf( "\n Size of double = %d", sizeof(double));
  printf( "\n Size of 'a' = %d", sizeof('a'));
  printf( "\n Size of 3*6+2 = %d", sizeof(3*6+2));
  printf( "\n Size of pi = %d", sizeof(22.0 / 7.0));
  printf( "\n Size of \"abcd\" = %d", sizeof("abcd"));
  return 0;
}

Program in C++ :

#include<iostream>
using namespace std;
int main() {
  cout << "\n Size of char datatype = " << sizeof(char);
  cout << "\n Size of int datatype = " << sizeof(int);
  cout << "\n Size of float datatype = " << sizeof(float);
  cout << "\n Size of double = " << sizeof(double);
  cout << "\n Size of 'a' = " << sizeof('a');
  cout << "\n Size of 3*6+2 = " << sizeof(3*6+2);
  cout << "\n Size of pi = " << sizeof(22.0 / 7.0);
  cout << "\n Size of \"abcd\" = " << sizeof("abcd");
  return 0;
}

Output-

sizeof() output

Parts of program-

1. #include is a pre-processor directive. It is used to include header files.
2. stdio/iostream is header file which has certain commands that c/c++ supports. E.g. return, main, etc.
3. .h is an extension for header file.
4. char, int, float, double are datatypes.
5. main() is main function that indicates the compiler that the user written programs starts from here.
6. printf/cout is the keyword use to print a message.
7. return statement is use to return a value. If any error occurs the program will return 0.

Conclusion-

So this is the use of sizeof() operator in C/C++. We hope it was clear to you. If you find it useful then do share it with your programming buddies and friends. Also if you have any doubt regarding any post do tell us in the comment section.

For daily updates do follow us on Instagram. Visit again!

ErrorFreeProgram.

1 COMMENT

Leave a Reply

Your email address will not be published. Required fields are marked *