In the C programming language, a variable is a defined memory area that holds a specific value of a particular data type. Each variable is identified by a unique name and is associated with a data type that defines the kind of data it can store.
Syntax
The format for declaring a variable in C is as shown below:
data_type variable_name;
In this particular format,
- data_type signifies the category of data (e.g., int, char, float, double, etc.) that the variable is capable of storing.
- variable_name serves as the label for the variable, denoting its specific name.
Simple Example of C Variable
Let's consider a scenario to demonstrate the concept of variables in the C programming language.
Example
#include<stdio.h>
int main() { //main function
// Here, value1 and value2 are the variables
int value1; // variable declared
value1=10; // variable initialized
char value2 = 'T'; // variable declared and initialized
//Declaring multiple variable of float type together
float f1, f2, f3;
f1 = 10.9; // Initialized the floating variable f1
f2 = 3.5; // Initialized the floating variable f1
f3 = 6.1; // Initialized the floating variable f1
// Accessing the variables initialized
printf("The integer value stored in variable value1 is : %d \n \n ", value1);
printf("The character value stored in variable value2 is : %c \n \n ", value2);
printf("The float type values stored in variables f1, f2, f3 are : \n %f \n %f \n %f \n \n ", f1, f2, f3);
return 0;
}
Output:
The integer value stored in variable value1 is : 10
The character value stored in variable value2 is : T
The float type values stored in variables f1, f2, f3 are :
10.900000
3.500000
6.100000
Explanation:
In this instance, we've established various variables to contain diverse data types. Value1 stores integer input, Value2 stores character input, while F1, F2, and F3 store float input values. These variable names are employed for storing user input in the system's memory, eliminating the requirement to recall their memory locations.
Rules for Declaring a C Variable
In C, Variable names must follow a few rules to be valid. The following are the rules for naming variables in C:
- Allowed Characters: Variable names include letters (uppercase and lowercase), digits, and underscores. They must start with a letter (uppercase or lowercase) or an underscore (_).
- Case Sensitivity: C is a case-sensitive programming language. It means that uppercase and lowercase letters are considered distinct. For example, myVar, MyVar, and myvar are all considered different variable names.
- Keywords: Variable names cannot be the same as C keywords (reserved words) because they have special meanings in the language. For example, we cannot use int, float, char, for, while, etc., as variable names.
- Length Limitation: There is no standard limit for the length of variable names in C. It is better to keep them reasonably short and descriptive. Some compilers may impose a maximum length for variable names.
- Spaces and Special Characters: Variable names cannot contain spaces or special characters (such as !, @, #, $, %, ^, &, *, (, ), -, +, =, [, ], {, }, |, \, /, <, >,., ?;, ', or "). Underscores are the only allowed special characters in variable names.
- Reserved Identifiers: While not strictly a rule, it is advisable to avoid specific patterns or identifiers common in libraries or standard usage. For example, variables starting with __ (double underscores) are typically reserved for system or compiler-specific usage.
Valid and invalid variable names in C
There exist numerous acceptable and unacceptable variable identifiers. A selection of these is outlined below:
Valid Variable Names
- int age;
- float salary;
- char _status;
- double average_score;
- int studentCount;
Invalid Variable Names
- int 1stNumber; // Starts with a digit
- float my-salary; // Contains a hyphen (-)
- char int; // Same as a C keyword
- int double; // Same as a C keyword
- float my$var; // Contains an unsupported special character
Variable Declaration
In C programming, the act of informing the compiler about a variable's presence and its data type is referred to as variable declaration. This action serves to inform the compiler that a certain variable, identified by a particular name and data type, will be utilized within the program. However, it does not yet reserve memory for the variable. Variable declarations are typically encountered at the beginning of a function or block, prior to the variable being used.
Syntax
The general syntax for variable declaration is
data_type variable_name;
Example of Variable Declaration
Let's consider an example to demonstrate the process of declaring variables in the C programming language.
Example
#include <stdio.h>
int main() {
// Variable declaration
int age;
float salary;
char initial;
return 0;
}
Variable Definition
In C programming, the act of allocating memory space for a variable to store its assigned value throughout program execution is referred to as variable declaration. This process is dependent on the data type specified for the variable, linking the variable name to a specific memory location of appropriate capacity. While a variable can be declared and defined within a single statement, there is also the option to separate these actions if required.
Variable Initialization
In C programming, declaring a variable involves notifying the compiler of the variable's data type and existence. This declaration specifies a variable's name and data type within the program, but it does not assign memory to the variable. Uninitialized variables may hold random data, leading to unpredictable program outcomes.
Example of Variable Initialization
Let's consider an example to demonstrate how variables are initialized in the C programming language.
Example
#include <stdio.h>
int main() { //main function
// Variable definition and initialization
int age = 25;
float salary = 2500.5;
char initial = 'J';
// Display initial values
printf("Initial age: %d\n", age);
printf("Initial salary: %.2f\n", salary);
printf("Initial: %c\n", initial);
// Change the value of the variables
age = 30;
salary = 3000.0;
// Display updated values
printf("Updated age: %d\n", age);
printf("Updated salary: %.2f\n", salary);
return 0;
}
Output:
Initial age: 25
Initial salary: 2500.50
Initial: J
Updated age: 30
Updated salary: 3000.00
Explanation:
In the illustration provided, we have introduced variables such as age, salary, and initial declarations. Subsequently, we proceed to declare and assign initial values to these variables (e.g., age = 25). As the program progresses, it becomes possible to alter the values held by these variables (e.g., age = 30).
Type of C Variables
There exist various kinds of variables in the C programming language. A few examples are outlined below:
Now, we will discuss every variable one by one.
Local Variable
In C programming, a local variable is a variable declared within a specific method or block scope. The declaration of a local variable should occur at the beginning of the block. This requirement implies that a local variable must be initialized prior to any usage.
Example of Using Local Variable
Let's consider an example to demonstrate the concept of a local variable in the C programming language.
Example
#include <stdio.h>
int main( ) { //main function
// Defined the local variable x
int x=10;
printf("The value assigned to the local variable is : %d ", x );
return 0;
}
Output:
The value assigned to the local variable is : 10
Explanation:
In this instance, a local integer variable, denoted as x, is declared within the main function with an initial value of 10. Subsequently, the printf function is employed to exhibit the value assigned to x on the output screen.
Global Variable
In C programming, a global variable is a variable declared outside any function or block. Any function has the ability to alter the value of a global variable, as it is accessible to all functions. Declaration of a global variable is required at the beginning of the block.
Example of Using Global Variable
Let's consider an example to demonstrate the concept of a global variable in the C programming language.
Example
#include <stdio.h>
// Defining the global variable
int value=20;
int main() { //main function
// Defining the local variable
int x=10;
printf("The value assigned to local variable is : %d\n", value );
printf("The value assigned to global variable is : %d", x );
}
Output:
The value assigned to local variable is : 20
The value assigned to global variable is : 10
Explanation:
In this instance, we have assigned the value as a global variable accessible across the entire program, whereas x is a local variable defined within the main function. Subsequently, the printf function showcases the values of both variables.
Static Variable
In the realm of C programming, a static variable is a variable defined using the 'static' keyword. Such a variable preserves its value across successive function invocations.
Example of Static Variable in C
Let's consider a scenario to demonstrate the utilization of a static variable in the C programming language.
Example
#include <stdio.h>
int main( ) { //main function
// Defining the local variable
int x=10;
// Defining the static variable
static int y=10;
x=x+1;
y=y+1;
printf("The value assigned to local variable is : %d\n", x );
printf("The value assigned to static variable is : %d ", y );
}
Output:
The value assigned to local variable is : 11
The value assigned to static variable is : 11
Explanation:
In this instance, we've chosen x as a local variable and y as a static variable. Each variable is increased by 1, leading to x = 11 and y = 11. The primary distinction lies in the fact that x is reset each time the function is executed, whereas y maintains its value across function invocations.
Automatic Variable
In the C programming language, all variables defined within a block are considered automatic variables by default. Additionally, we have the option to explicitly define an automatic variable using the auto keyword.
Example of Automatic Variable in C
Let's consider an example to demonstrate the automatic variable in the C programming language.
Example
#include <stdio.h>
void display() { // user-defined function
int x = 10; // automatic variable (implicitly)
auto int y = 20; // automatic variable (explicitly using auto)
// Performing operations
x = x + 15;
y = y + 25;
// Displaying values
printf("Value of a (auto by default): %d\n", x);
printf("Value of b (explicit auto): %d\n", y);
}
int main() { // main function
display(); // calling the function
return 0;
}
Output:
Value of a (auto by default): 25
Value of b (explicit auto): 45
Explanation:
In this instance, both variable a and variable b are considered automatic variables, signifying that their memory is assigned automatically upon the function's invocation and released when the function concludes.
External Variable
In C programming, it is possible to have a variable shared across multiple source files by utilizing an external variable. When declaring an external variable, the extern keyword is required.
Syntax
It has the following syntax:
extern data_type var_name //external variable (also global)
Example of Extern Variable in C
Let's consider an example to demonstrate the use of an extern variable in the C programming language.
myfile.h
extern int x=10;//external variable (also global)
program1.c
Example
#include "myfile.h"
#include <stdio.
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}
Scope of Variable in C
In C programming, the scope of a variable indicates the specific section of the code where the variable can be accessed or utilized. C offers various scopes based on the declaration location and method. Typically, a scope encompasses the code enclosed within {} curly brackets.
Conclusion
In summary, variables play a crucial role in the C programming language by storing and handling data in the computer's memory. They act as named placeholders for memory locations, simplifying the process of accessing and manipulating stored information. Adhering to certain guidelines, like commencing variable names with a letter or underscore and avoiding reserved words, guarantees the creation of valid variable identifiers.
In the C programming language, variables are flexible in terms of initialization. They can either be declared without an initial value or assigned a value when they are declared. After declaration, these variables are accessible and can be employed across the program to hold and process data. If necessary, the variables can be updated with fresh values as the program runs.