Variable in C Language

  Variable in C Language


What is an identifier or Variable?

An identifier is the name given to entities such as variables, functions, structures etc. Variable is an identifier which is used to store data or value. Variables can change during execution but constants can remain constant during execution of the program.  Declared variables can be used in programs at multiple locations for different operations. 

A variable is a storage place that has some memory allocated to it.

Variable is a container which holds a value or data. 

For example,

int  rollno;

char  name;

Float balance;

In above examples rollno, name and balance are identifiers.

Identifiers or variable names must be different from the keywords. For example we can not use int as a variable name because int is a keyword.

Following are Rules for Identifiers or Variables:

1. The identifier can have an alphabet(either uppercase A-Z and lowercase a-z alphabets) ,underscores(_) and digits(0 to 9).

2. First letter of an identifier should be either a letter or an underscore.

3. There is no rule on how long the identifier can be.

4. We cannot use keywords like int, get, for, while etc as an identifier

5. White space is not allowed within variable name


For example,

int  rollno;  // Valid declaration

Char sex=’M’; //valid declaration

rollno;  // invalid declaration

float principle amount; // invalid declaration because white space is not allowed

float  principle_amount; // valid declaration


For example,

#include<stdio.h>

#include<conio.h>

void main()

{

int a=10;

int b=10;

float sum =15.50;

printf(“The sum=%f”,a+b);

}


Here a, b and sum are variables with its data type int and float.  The a variable holds 10 integer value, b variable holds 10 integer value and sum variable holds float value 15.50. A variable value can be changed hence it is named as variable. 

Constants in C Language: 

The constants in C language hold the values that can not change during the execution of a program. Constants are any type of basic data types like integer constants, float constants, character constants or string constants. 

In C language there are two ways to use constants,

1. Using #define preprocessor :

Syntax:

#define variable_name value


e.g.  #define pi=3.14;


#include<stdio.h>

#define pi 3.14


void main()

{

    int r=10;

    float area;

    area=pi*r*r;

    printf("%f",area);

}

Output:

314.000000


2. Using const Keyword:

Syntax:

const  type variable = value;


e.g.  

const  float pi = 3.14; 


#include<stdio.h>

//#define pi 3.14


void main()

{

    int r=10;

    float area;

    const float pi =3.14;

    area=pi*r*r;

    printf("%f",area);

}

Output:

314.000000











टिप्पणी पोस्ट करा

0 टिप्पण्या