This blog is under construction

Friday, 27 December 2013

What is a variable in c language?

Variable is a symbolic name to a memory location and it can be assigned some values. Basically, variable needs to be declared with appropriate data type before using it. Below is an example for a variable declaration.

int           num;
where int is the integer datatype and num is the variable name.

Consider the below example

Here, num is variable name.  In other words, it is the symbolic name for the memory location 0x1234567. Since the variable num is not initialized, it has some junk value in it(value inside the box - 43245).

Junk value stored in the variables can be avoided through proper initialization.  Let us initialize the variable num with a value and check the behavior.
int num = 20;

Now, we have initialized the variable with value 20 and it doesn't have any junk value.

Value of the variable can be changed anytime(ie) the contents inside the box can be changed any time.
num = 30;

Now, the value of the variable num has changed to 30(value inside the box).

Variables need to be declared at the top of a function.  Same name to multiple variables is not allowed.  Below are the valid characters for variable name
   0-9, A-Z, a-z, "_", $

Why variables need to be declared before using them?
Let us try to understand with a simple example c program.
  #include <stdio.h>
  main() {
        num = 10;
        printf("Value of num is %d\n", num);
        int num;

  jp@jp-VirtualBox:~/$ gcc var.c 
  var.c: In function ‘main’:
  var.c:3: error: ‘num’ undeclared (first use in this function)
  var.c:3: error: (Each undeclared identifier is reported only once
  var.c:3: error: for each function it appears in.)

In the above program, we have assigned value 10 to the variable num and trying to print the value of num.  Here, we have done the variable declaration after assigning value to the variable num.  On compiling the program, it throws the above error messages as it detects no declaration for variable num prior to assigning num with value 10. Basically, compiler would expect variable to be declared before its usage.  And the above error can be resolved by moving declaration part prior to assigning num with value 10.

Why we need to initialize variable before using it?
  #include <stdio.h>
  main() {
        int num;
        printf("Value of num before initialization: %d\n", num);
        num = 10;
        printf("Value of num after initialization: %d\n", num);

  jp@jp-VirtualBox:~/$ ./a.out
  Value of num before initialization: 8769524
  Value of num after initialization: 10

If the variables are not initialized, then they will hold garbage values.  We will get undesired results, if we do any manipulation with garbage values.

No comments:

Post a Comment