Tuesday, February 6, 2018

Coding using keywords- part 8 (sizeof)

sizeof keyword in C is to easiest way to know the number of bytes of a variable inside the RAM.


So let's take an example of sizeof with data types:

  1. #include<iostream>  
  2. using namespace std;  
  3. int main() {  
  4.     int a = 1;double b = 4.00;float c = 5.00;char qw = 'a';  
  5.     int *ptr;  
  6.     cout << "The size of a :" << sizeof(a)  
  7.         << "\nThe size of b :" << sizeof(b)  
  8.         << "\nThe size of c :" << sizeof(c)  
  9.         << "\nThe size of qw :" << sizeof(qw)  
  10.         << "\nThe size of pointer :" << sizeof(ptr)<<endl;  
  11.     system("pause");  
  12.     return 0;  
  13. }  

Output:

The size of a :4
The size of b :8
The size of c :4
The size of qw :1
The size of pointer :4

Press any key to continue . . .

Explanation


As I mentioned inside my blog https://philippebalech.blogspot.com/2018/01/variables-in-cc.html, each variable takes place in RAM with different value of bytes. You can check the number of bytes each variable take, by using the sizeof keyword. I should also say that the pointer will point on an int type; even if it's not pointing on anything you can check its size easily.

Tips


sizeof may be also used to know the number of elements inside an array. An array is a set of different variables with the same data type; the number of elements declared inside the array will be shown in a block of memory one after the other with the same type. So how can you know the number of elements inside the array just by using sizeof.

  1. #include<stdio.h>  
  2. int main()  
  3. {  
  4.     int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };  
  5.     printf("Number of elements inside the array :%d",   
  6.         sizeof(arr) / sizeof(arr[0]));  
  7.     return 0;  
  8. }  


Output

Number of elements inside the array : 8

Explanation


By using sizeof(arr), the user can know the place that the whole array took inside the RAM. In this example (32 bits) since 8 integer elements. By dividing the whole number onto the place that a single integer takes inside the RAM you can know the number of elements that the array contains.

No comments:

Post a Comment