In computer programming, a variable is a named container that is associated with the storage location in the computer’s physical memory. Before designing and using the suitable variable name, we must declare and define it. A declaration is the creation of a variable name, whereas the definition is the assignment of some value to it.
The general syntax for declaring a variable is:
type_qualifier data_type variable_name1, variable_name2,...., variable_namen;
The general syntax for variable declaration with a definition is
type_qualifier data_type variable_name1 = INITIAL_VALUE;
Example:
// declaring single variable of type unsigned long integer
unsigned long int my_var;
// declaring three variables of type int x,y,z
int x, y, z;
// declare x of type integer and initialize with 30
int x = 30;
// * to make run these statements, you must write it inside main function
// * Check what happens if you assign a value to a variable that is
// out of range to that container
Constant declaration, definition:
The constants do not allow update or change once it is initialized. In C, we use keyword const to make a variable of type constant. Constant should be initialized during the declaration. The general syntax for creating a constant in C is.
type_qualifier data_type constant_name = VALUE;
Example
// declaring value of pie as constant
unsigned float PI = 3.1416;
The following is the sample example that can be run with a C compiler or IDE:
/*
simple program to demonstrate variable and constants
in C Programming
*/
#include <stdio.h>
int main()
{
char my_character = 'A';
int my_integer = 1;
const float PI = 100;
// print the current values of the variables and constants
printf("Value of Character: %c\n", my_character);
printf("Value of Integer: %d\n", my_integer);
printf("Value of PI: %f\n", PI);
// you can change the value of variable
my_integer = 123;
// print changed value
printf("New Value of Integer: %d\n", my_integer);
// if you try to change the value of constant compiler will flag
return 0;
}
The Expected output is:
Value of Character: A
Value of Integer: 1
Value of PI: 100.000000
New Value of Integer: 123