C - Variables


Variables In C, variable is a data name given to a data value stored in the memory and can vary at the time of execution. Name of the variable should be meaningful and in C there are some rules are defined for naming variables and rules to declare C Variables is that alphabets, digits and underscore, begins with the alphabets or underscores (_) and digits (0-9) and keyword cannot be used as a keyword. Here eitworld.com provides the learning tutorial of C variable with examples.

  • A variable is a data name given to a data value stored in the memory.
  • The value of variable can vary at the time of execution.
  • Name of the variable should be meaningful and in C there are some rules are defined for naming variables which are as follows:

Rules for naming Variable

  • Variable name may contain letters, digits and underscore (_) character.
  • The variable name can begin with the letters as well as with underscore (_) character.
  • A variable name should not start with digit.
  • A variable name cannot contain punctuation characters like (@,#,$,%,^,&,* etc)
  • A variable name cannot be a keyword.
  • The variable names may be a combination of uppercase and lowercase characters. For example name and naME are not the same.
45, -16, +56, 67 etc.

Variable Declaration in C

  • Declaration of a variable is necessary before using it into the program.
  • A variable is declared using a data type and a meaningful variable name. The basic syntax of variable declaration is as follows:
  • Data_type variable_name;
  • A variable can be of any data type like int, float, double and char etc.
  • Here are some examples of variable declaration:
  • int age;

    float area;

    char m;

    int a,b,c;/*More than one variable of same type can be declare in single statement.*/

Initializing Variable

  • Variable can be initialized using the assignment operator '='.
  • Variable declaration and initialization can also done in same line.
  • The basic syntax to initialize a variable is as follows:
  • variable_name=data_value;

    ----OR-----

    Data_type variable_name=data_value;

  • Some examples of declaring constant in C++ are given here:
  • const int a=10; const float b=10.34; const char c='a';
  • Here is an example of variable initialization:
  • int x;

    x=3;

    ----OR----

    int x=3;

Here is an example of using variable in C program:

#include<stdio.h>

int main()

{

int a;/*Variable declaration*/

a=5;/*Variable initialization*/

printf("\nvalue of a is:%d",a);

return 0;

}
  • The output of the above program is as follows:
  • value of a is:5