A variable in C is the name given to a memory location, where a program can store data. To uniquely identify a memory location, each variable must have a unique identifier. A program can store and manipulate the value stored using variable's identifier. Variables must be defined before their use in a program.
- A variable's name can be composed of alphabets, digits, and underscore only.
- The first character of a variable name must be either an alphabet or underscore.
- Variable name is case sensitive. Home and home is recognised as two separate identifiers.
- Any special characters other than alphabets, digits, and underscore (such as :, . ,blank space, / are not allowed).
Declaration and Initialization of Variable in C
A variable can be of any data type like char, int, double etc. Declaration of a variable in C associate it with a data type which defines the size, how it's value should be stored in memory, the range of values that can be stored and the set of valid operations for that variable.
Syntax for Declaring a Variablefloat sum;
In the above statement we are declaring some memory space for a variable called sum, to store a floating point data.
Multiple variables of same data type can be declared by separating the variable names by comma.
int sum, amount, interest;
We can initialize a variable with some value at the time of declaration. The initialization statement consists of an equal sign followed by a constant after variable name.
int sum = 0;
float rate = 5.5, amount = 345.52;
Difference between Variable Declaration and Definition in C
- Declaration of a variable declares the name and type of the variable whereas definition causes storage to be allocated for the variable.
- There can be more than one declaration of the same variable but there can be only one definition for the variable.
- In most cases, variable declaration and definition are same. However you can declare a variable without defining it by preceding a variable name with extern specifier.
Local Variable in C
A local variable in C is declared inside a function.
- A local variable is visible only inside their function, only statements inside function can access that local variable.
- Local variables are declared when control enters a function and local variables gets destroyed, when control exits from function.
#include <stdio.h> int getSum(int var1, int var2){ int sum = var1 + var2; return sum; } int main(){ int a = 5, b = 10; printf("Sum = %d", getSum(a, b)); return 0; }In above program, variable a and b are local variables of main function similarly var1 and var2 are local variables of getSum. Variables a and b are only accessible from main function.
Output
Sum = 15
Global Variable in C
A variable that is declared outside of all functions is called global variable.
- A global variable is visible to any every function and can be used by any piece of code.
- Unlike local variable, global variables retain their values between function calls and throughout the program execution.
- Global variables are declared outside of any function.
#include <stdio.h> int sum; void getSum(int var1, int var2){ sum = var1 + var2; } int main(){ int a = 5, b = 10; getSum(a, b); /* Accessing global variable from main*/ printf("Sum = %d", sum); return 0; }In above program, variable sum is a global variable because it is declared outside of any function. Variable sum can be accessed from any function.
Output
Sum = 15
Dynamic Memory Allocation
- malloc : The malloc function is used to allocate a specified number of bytes of memory and returns a pointer to the first byte of the allocated memory.
int *dynamicArray = (int *)malloc(5 * sizeof(int));
In this example, dynamicArray is a pointer to the first element of an array of five integers. - free : The free function is used to release the memory previously allocated by malloc.
free(dynamicArray);
Failing to free dynamically allocated memory can lead to memory leaks, where the program uses more and more memory without releasing it.
Best Practices for Variable Usage in C
- Use Descriptive Names : Choose meaningful and descriptive names for your variables. This makes the code more readable and helps others (or even yourself) understand the purpose of the variable.
// Avoid: int x; // Prefer: int userAge;
- Initialize Variables Before Use : Always initialize variables before using them. Uninitialized variables can contain garbage values, leading to unpredictable behavior.
// Avoid: int total; total = total + 10; // Using uninitialized variable // Prefer: int total = 0; total = total + 10; // Initializing before use
- Limit Variable Scope : Limit the range of variables as much as you can. This lessens the possibility of unforeseen adverse effects and facilitates comprehension of the program's flow.
// Avoid: int globalVar = 10; void myFunction() { // Accessing globalVar here } // Prefer: void myFunction() { // localVar is only accessible within this function int localVar = 42; // Work with localVar here }
- Avoid Global Variables When Possible : Though global variables can be helpful sometimes, it's best to use them as little as possible. It's possible that some parts of your code will use global variables in ways that you didn't intend.
- Constants for Magic Numbers : "Magic numbers" are numbers that are hard-coded and should not be used in your code. If you must use values, give them names that describe their function. This facilitates future changes to the integers and makes the code more readable.
// Avoid: float calculateTax(float income) { return income * 0.15; // What does 0.15 represent? } // Prefer: const float TAX_RATE = 0.15; float calculateTax(float income) { return income * TAX_RATE; }
- Be Mindful of Memory Usage : Consider the data types and storage capacity of your variables when memory efficiency is crucial. Select the lowest data type that is capable of holding your information.
// If the range of values is small: unsigned char smallValue = 10;
- Use Pointer Safety Measures : When working with pointers, keep in mind that they should not be dereferenced before being assigned a valid memory address. Before dereferencing, always check for NULL.
int *ptr = NULL; // Check before dereferencing if (ptr != NULL) { int value = *ptr; }
- Follow a Naming Convention : Establish a standard naming scheme for your variables. Adhering to a pattern, be it snake_case, camelCase, or another convention, improves code consistency.
// CamelCase: int numberOfStudents; // Snake_case: int number_of_students;
Conclusion
The fundamental units of any C program are variables, which let you store and manage data efficiently. This extensive tutorial addressed the fundamentals of declaring and initializing variables, as well as advanced subjects like constants, dynamic memory allocation, and pointers. It also covered a variety of data types and variable scope.