How Variable Work In C

Size of variable

Each type of variable will have a size. For example:

  • Size of int is 4
  • Size of char is 1
  • Size of a long is 8
  • Size of a pointer (int*, long*, char*) is 8

To verify the size of each type, we can run the following code

#include <stdio.h>

int main()
{
    printf("size of a short is %ld\n", sizeof(short));
    printf("size of a int is %ld\n", sizeof(int));
    printf("size of a long is %ld\n", sizeof(long));
    printf("size of a long pointer is %ld\n", sizeof(long*));
    printf("size of a int pointer is %ld\n", sizeof(int*));
    printf("size of a char pointer is %ld\n", sizeof(char*));
}

[!note]
The size of each one dependent on the machine type 64bit vs 32bit etc

Considering the following code:

int k;

When the compiler see int, it will assign 4 bytes of memory to hold the value of integer.

It setup a Symbol Table where it store the symbol k and its memory address and reserves 4 bytes.

Later on if we set

k = 2;

During rumtime, the compiler will assign the value 2 in the above reserved 4 bytes.

lvalue vs rvalue

In the example above where k = 2 the lvalue (left value) is k where it's before the = and rvalue (right value) is 2.

lvalue holds the value of the memory location whereas the rvalue holds the value of the variable (2)

For example, if we doing something like this:

int j, k;

k = 2;
j = 7; // A
k = j; // B

In (A), we have j is the lvalue which reserved 4 bytes and copy the value 7 to that address.

In (B), now j is rvalue, so that means the value of j (7) will be copied to k. Since j size is 4 bytes, we copy 4 bytes