C Variable

C  Variable:

• Variable is a named location in a memory where a program can manipulate the data. This location is used to hold the value of the variable.
• The value of the C variable may gets change in the program.
• C variable might be belonging to the data type such as int, char,float etc.

RULES FOR NAMING A VARIABLE:

1. Variable name begin with underscore or letter.
2. They are case sensitive.
3. They can be constructed with, letters, digits.

DECLARING & INITIALIZING C VARIABLE:

• Variables must be declared in the C program before to use.
• Memory space isn’t allocated for a variable while declaration. It allocted at the time variable definition.
• Variable initialization means assigns a value to the variable.

Type Syntax
Declaration of variable in C data_type variable_name;Example: int p, q, r; char flag, ch;
Variable initialization in C data_Type variable_name = value;Example: int p = 50, q= 30; char flag = ‘x’, ch=’l’;
THERE ARE THREE TYPES OF VARIABLES ARE,
1]Local variable
2]Global variable
3]Environment variable

1. EXAMPLE PROGRAM FOR LOCAL VARIABLE IN C:

• The life of local variables will be within the particular function only.

• These variables are declared within the function and these can’t be accessed outside the function.

Example

#include <stdio.h>

void test();

int main()

{

int m1 = 22, n1 = 44;

printf(“\nvalues : m1 = %d and n1 = %d”, m1, n1);

test();

}

void test()

{

int a1 = 50, b1 = 80;

printf(“\nvalues : a1 = %d and b1 = %d”, a1, b1);

}

Output

values : m1 = 22 and n1 = 44

values : a1 = 50 and b1 = 80

2. EXAMPLE PROGRAM FOR GLOBAL VARIABLE IN C:

• The life time of this variables will be throughout the program. These variables can accessible from anywhere in the program.
• This variable is defined outside the main function. So that, this variable is accessed to main function and all other sub functions.

Example

#include <stdio.h>

void test();

int m1 = 22, n1 = 44;

int a1 = 50, b1 = 80;

int main()

{

printf(“All variables are accessed from main function”);

printf(“\nvalues: m1=%d:n1=%d:a1=%d:b1=%d”, m1,n1,a1,b1); test();

}

void test()

{

printf(“\n\nAll variables are accessed from” \ ” test function”);

printf(“\nvalues: m1=%d:n1=%d:a1=%d:b1=%d”, m1,n1,a1,b1);

}

Output

All variables are accessed from main function

values : m = 22 : n = 44 : a = 50 : b = 80

All variables are accessed from test function

values : m = 22 : n = 44 : a = 50 : b = 80

Leave a Reply

Your email address will not be published. Required fields are marked *