Explain the variable declaration, initialization and assignment in C language


The main purpose of variables is to store data in memory. Unlike constants, it will not change during the program execution. However, its value may be changed during execution.

The variable declaration indicates that the operating system is going to reserve a piece of memory with that variable name.

Variable declaration

The syntax for variable declaration is as follows −

type variable_name;

or

type variable_name, variable_name, variable_name;

For example,

iInt a,b;
float c;
double d;

Here, a, b, c, d are variables. The int, float, double are the data types.

Variable initialization

The syntax for variable initialization is as follows −

data type variablename=value;

For example,

int width, height=20;
char letter='R';
float base, area; //variable declaration
double d;
/* actual initialization */
width = 10;
area = 26.5;

Variable Assignment

A variable assignment is a process of assigning a value to a variable.

For example,

int height = 40;
int base = 31;

Rules for defining variables

  • A variable may be alphabets, digits, and underscore.

  • A variable name can start with an alphabet, and an underscore but, can’t start with a digit.

  • Whitespace is not allowed in the variable name.

  • A variable name is not a reserved word or keyword. For example, int, goto etc.

Example

Following is the C program for variable assignment −

 Live Demo

#include <stdio.h>
int main (){
   /* variable definition: */
   int a, b;
   int c;
   float f;
   /* actual initialization */
   a = 40;
   b = 50;
   c = a + b;
   printf("value of c : %d 
", c);    return 0; }

Output

When the above program is executed, it produces the following result −

Value of c: 90

Updated on: 08-Mar-2021

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements