Declaration and Initialisation of Variables In C
Introduction for Declaration of Variables:
- In any programming language, variables are the most crucial component.
- Let's imagine we need to determine a rectangle's area. We need to keep a record of the rectangle's length and breadth so that we can perform this arithmetic calculation.
- We have to place out a space in memory for the data in order to store the length and width of the rectangle, and that memory address is given the name Variable.
- To make it easier for the programmer to use, we assign each type of data a unique variable name.
- Let's look at the next picture for a better understanding. A variable named my var with the value 22 is displayed along with the memory location where the data is kept.
Need and Purpose of Variable Declarations:
- In order to store multiple sorts of data in the program, we must declare a variable. We must therefore store the data in the computer's memory in order to conduct some actions or activities with it.
- However, we are unable to recall the memory location's address where the data is kept. We consequently assign a variable name and size based on the type of data to the memory location in order to access the data.
- By declaring a variable in the program, we must inform the compiler of the type of data to be accessed as well as the variable name.
- The main goal of variable declaration is to keep the necessary data in memory as variables so that we may use them throughout our programme to carry out any task or action.
- When a variable is declared, its name and appropriate data type can be used to access it in our program.
Basic syntax for declaration of the variables:
There are two ways to declare variables in variable declarations:
i. Declaration of a variable without assigning it any initial value
Syntax: data_type var_name;
Example: str Emp_Name; // Emp_Name is a char type variable with no value
assigned to it.
ii. Declaration of a variable with assigning it any initial value
Syntax: data_type var_name = value;
Example: int marks=75; // The value 75 is held by the int variable called marks.
- “Data_type” in this case indicates the type of a variable, such as an int, char, etc.
- "var_name" is used to specify the variable's name. The variable is being initialised for the value “value”.
Program to Demonstrate the Variable Declaration in C:
- We must define a variable with the appropriate data type and give it a value before we can utilise the data in the programme. then retrieve the data by using that variable name.
- A variable is not given any memory when it is declared. Only when the variable is initialised does it occur.
- If the variables are declared without initialising then, then it simply stores a zero or some other type of garbage value. On the other hand, the previous value will be overwritten if we provide it with a value.
#include <stdio.h>
int main()
{
// declaration of the variable 'a' with value 10.
int a = 5;
// declaration of the variable 'a' with value 10.
int b = 4;
// declaration of the variable 'c' without initialising it.
int c=0;
// checking a C variable's initial value.
printf("Initial value of the variable C is %d\n", c);
c= a + b;
// displaying the present C variable value.
printf("The sum of a and b equals %d", c);
return 0;
}
OUTPUT:
![Declaration and Initialisation of Variables In C](https://static.tutorialandexample.com/c/declaration-and-initialisation-of-variables-in-c1.png)
Explanation:
We can see from the programme above that the value of c is 0 at the beginning. When we reassign the old value to the C variable, the new one will replace the old one.
Types of Variable Declarations in C:
Before utilising a variable, it must first be declared in C by storing the variable's name and data type.
In C, variables can be declared in one of two ways:
- Primary Type Declaration
- User-Defined Type Declaration
1.Primary Type Declaration:
Primitive data types, often known as built-in data types, are declared in a variable using a primary type declaration.
Integer, float, character, Boolean, double, long, etc. are the primary data types that are used the most frequently.
a). Single primary type declaration:
Example: char Marks_Grade= 'A';
b). Multiple primary type declarations in the same line
The example that follows demonstrates how to divide variables that are specified on the same line with a comma.
Example: int Length= 7, Breadth = 4, Height = 6;
c). Multiple primary type declaration in different lines
Semicolons must be used to separate variables when they are defined on different lines, as it's shown in the example below.
Example: int var_name1 = 4;
float var_name2 = 44.44;
char var_name3 = 'J';
2.User-Defined Type Declaration:
A data type that has been defined by the user in a declaration, which is a type of declaration, is known as a user-defined type.
The most popular data types include structures, unions, enums, typedefs, etc.
a). Structure:
In order to create a single user-defined data type, structures are used to mix several types of data parts.
b). Union:
Any one of the members of a union, which is a user-defined data type, can be accessed at once because they all share the same memory space. When there is only one member we need, we use a union.
c). Typedef:
For the purpose of defining the data type, the phrase typedef must be used. Those new data types are now available for usage in our program, as demonstrated in the example below.
Example:
typedef char Emp_name;
typedef int Emp_age;
typedef float Emp_sal;
We are able to develop our own data kinds by utilising user-defined data types. The name, age, and salary of a person can be stored in a new data type we can build called person_info, for instance. Also makes the program easier to read.
NOTE:
- A primary type declaration allows us to utilise any variable name for any data type, which is the main difference between it and a user-defined type declaration.
- In the user-defined type declaration, we are permitted to use any identifier for any data type.
C Variable Declaration Rules:
- Declaring two variables with the same name within the same scope is inappropriate.
- Any character, including the alphabet and the underscore, can begin a variable name. However, a number shouldn't be the first character in the variable name.
- In C, a reserved keyword cannot be used to name a variable. For instance, a variable name cannot be used as a variable name if it is declared as a label, int, float, char, function, otherwise, etc.
- Any combination of alphabets, numerals, and underscores may be used in a variable name.
- A semicolon must follow each declaration statement. (;)
- It will be preferable if we declare variables with meaningful names that then explicitly state what they are used for.
In what way do variables get initialized in C?
- Variables are able to be initialised in the declaration statement within any block in the C programming language, including the main block and any function-specific blocks.
- The assignment operator can be used to assign a value to a variable while it is being declared.
- The process of giving a variable a value is known as initialization. Each programming language has a unique procedure for initialising variables. The procedure is only known as a Declaration if the value is not applied to the Variable.
- The basic syntax of the initialization of Variables is :
data_type vari_name=constants/ literals/ expressions;
or
vari_name=constants/ literals/ expressions;
Example:
int x=4;
int x=y+z;
x=4;
x=y+z;
Initialization of Variables for different Variables:
- Initialising the integer variables:
Example:
int num=15;
- Initialising the floating-point variables:
Example:
float value = 44.4f;
- Initialization of character variables:
Example:
char gender='F';
- Initialization of character or string Array:
Example:
char country_name[] = "John Smith" OR
char student_name[10] = "John Smith";
/* The maximum number of characters allowed here is 10. */
- Initialization of an integer Array:
Example:
int arr[]=1, 5, 9, 7, 3; OR
int arr[5]=1, 5, 9, 7, 3;
Some of the Constraints to initialize the variables are mentioned below:
When assigning values to variables, there are a few standards that must be maintained to :
- For instance, some programming languages, such as PHP, Python, and Perl, do not require the data type to be specified at the beginning.
- When assigning a value to a variable, always use the equals operator.
- A comma shouldn't be used with numerals.
- Only that particular form of data can be put in a variable once a data type has been declared for it. For instance, a variable can only store integer values if its type is declared as Int.
- Once defined, a variable name can only be used once more in the program's code. It cannot be redefined once more to store a different kind of value.
- The previous value will be replaced with the new value if another value is assigned to a variable that has previously had a value which is assigned to it.
Need of Initialization of the variables:
- Programming relies heavily on initialization since the variables that make up the code take up a specific amount of CPU memory.
- The CPU will assign the variable value to anything that is permissible in computer programming language if the memory values are not declared by the user at the beginning of the code's execution; this is commonly referred to as trash value.
- The logic of the programme will change if a variable has a garbage value set for it, which will produce an output with the wrong value.
- Some compilers even fail to assign a garbage value to the variable, which results in a null value for the variable and can also cause a compile-time error.
- As a result, initializing the variables is important.
- If variables are not initialized, then if possible, the variable values need to be modified to get rid of the invalid data and have a valid value for the variable that will ensure that the program produces the correct output.
Types of Initializations of Variables in C:
Majorly classified into 2 types. They are:
- Static Initialization
- Dynamic Initialization
1.Static Initialization:
With this approach, a value is predetermined for the variable. In this case, the declaration statement contains values that are assigned. Explicit Initialization and Static Initialization which are two terms used similarly.
Example:
int x;
x = 5;
int y = 10;
int a = 4, b = 5;
2.Dynamic Initialization:
The variable is given a value in this procedure at runtime. The value is either given by the program's function or by the user when the program is being used. Every time the program is executed, the values of these variables can be changed. Implicit Initialization is another name for dynamic initialization.
Example:
int number;
printf("Enter the value for the number");
scanf("%d", &number);
A single value may be used to initialize many variables in a single statement:
Example:
// C program to demonstrate the initialization of no of variables in single statement //
#include<stdio.h>
void main()
{
int a, b, c, d, e; // Declaration of the variables
a=b=c=d=e=4; // initialization of the variables
printf("%d \n",a);
printf("%d \n",b);
printf("%d \n",c);
printf("%d \n",d);
printf("%d \n",e);
}
Output:
![Declaration and Initialisation of Variables In C](https://static.tutorialandexample.com/c/declaration-and-initialisation-of-variables-in-c2.png)