Back to C Programming
2026-07-126 min read

Video: Variables in C Programming

Learn Video: Variables in C Programming step by step with clear examples and exercises.

Why This Matters

Understanding variables is crucial for mastering C programming as they serve as containers to store data values. Variables are essential for creating dynamic programs that can change and adapt based on user input or program logic. In this lesson, we will delve into the world of C variables, exploring their types, declarations, and usage in practical examples.

Prerequisites

Before diving into variables, it's important to have a solid understanding of the following topics:

  1. Basics of C programming syntax, including variables, operators, and expressions.
  2. Control structures such as if-else statements and loops (for and while).
  3. Basic I/O operations using printf() and scanf() functions.
  4. Understanding pointers and memory management in C.
  5. Familiarity with data structures like arrays and linked lists.

Core Concept

Variable Declaration

To create a variable in C, you first need to declare it by specifying its name, data type, and optional initial value. The syntax for declaring a variable is as follows:

data_type variable_name; // without initialization
data_type variable_name = initial_value; // with initialization

For example:

int age = 20; // Declaring and initializing an integer variable named 'age'
float pi = 3.14; // Declaring and initializing a floating-point variable named 'pi'
char grade; // Declaring an uninitialized character variable named 'grade'

Variable Types

C supports several data types, including:

  1. Integer (int): Used for whole numbers, such as 5 or -23.
  2. Floating-point (float or double): Used for decimal numbers, like 3.14 or 0.007.
  3. Character (char): Used to store individual characters, such as 'A' or '%'.
  4. Boolean (bool): Introduced in C99, used to represent true (1) and false (0).
  5. Enumerated (enum): A user-defined data type that represents a set of named integer constants.
  6. Pointer (void, int, char*, etc.): Used to store memory addresses of variables or data structures.
  7. Array: A collection of variables of the same data type, indexed by an integer.
  8. Structures: User-defined data types that group related variables together.

Variable Scope

In C, variables have a specific scope that determines their visibility within the program. The three main scopes are:

  1. Local variables: Declared inside functions and only accessible within that function.
  2. Global variables: Declared outside of any function and accessible from anywhere in the program.
  3. Static variables: Declared with the 'static' keyword, which makes them retain their value between function calls.

Memory Allocation

When you declare a variable, C automatically allocates memory for it on the stack or heap, depending on its data type and scope. The size of the allocated memory is determined by the data type:

  • int variables occupy 4 bytes (32 bits) on most systems.
  • float variables occupy 4 bytes (32 bits).
  • double variables occupy 8 bytes (64 bits).
  • char variables occupy 1 byte (8 bits).
  • Pointers require 4 or 8 bytes depending on the system architecture.

Dynamic Memory Allocation

In addition to static memory allocation, C allows for dynamic memory allocation using functions like malloc(), calloc(), and realloc(). This enables you to create variables (or data structures) of arbitrary size at runtime.

Worked Example

Let's create a simple C program that demonstrates variable usage:

#include <stdio.h>
#include <stdlib.h>

int main() {
int age = 20; // Declaring and initializing an integer variable 'age'
float pi = 3.14; // Declaring and initializing a floating-point variable 'pi'
char grade; // Declaring an uninitialized character variable 'grade'

printf("Enter your age: ");
scanf("%d", &age); // Reading user input into the 'age' variable

printf("\nYour age is now %d\n", age); // Printing the updated value of 'age'

printf("The value of pi is %.2f\n", pi); // Printing the value of 'pi' with 2 decimal places

printf("Enter your grade (A-F): ");
scanf(" %c", &grade); // Reading user input into the 'grade' variable (using a space to skip any leading whitespace)

switch(grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Good job!\n");
break;
case 'C':
printf("Keep improving.\n");
break;
case 'D':
printf("You need to study more.\n");
break;
case 'F':
printf("Please try again.\n");
break;
default:
printf("Invalid input. Please enter a grade between A and F.\n");
}

// Dynamic memory allocation for an array of 10 integers
int *numbers = (int*) malloc(10 * sizeof(int));
if (numbers == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Reading user input into the dynamically allocated array 'numbers'
for (int i = 0; i < 10; ++i) {
printf("Enter number %d: ", i + 1);
scanf("%d", numbers + i);
}

// Calculating and printing the average of the numbers in 'numbers'
float sum = 0.0f;
for (int i = 0; i < 10; ++i) {
sum += numbers[i];
}
printf("The average of the numbers is %.2f\n", sum / 10);

// Freeing the dynamically allocated memory
free(numbers);

return 0;
}

Common Mistakes

  1. Forgetting to initialize a variable: This can lead to unpredictable behavior, as the variable will contain random values from memory.
  2. Using the wrong data type for a variable: Using an integer variable for decimal numbers or vice versa can result in unexpected results and truncation errors.
  3. Mixing up assignment and comparison operators: Be sure to use = for assignment and == for comparison. For example:
int x = 5;
if (x = 10) { // Mistake! Assigns 10 to 'x' and checks if the result is true, which it isn't
printf("x equals 10\n");
}
  1. Accessing undefined variables: Make sure you have declared all necessary variables before using them in your code.
  2. Leaking memory: Be mindful of dynamically allocated memory and always free it when it's no longer needed to avoid memory leaks.
  3. Forgetting to include required header files: Ensure you have the correct header files included for the functions you are using, such as stdio.h for I/O operations and stdlib.h for dynamic memory allocation.

Practice Questions

  1. Write a program that calculates the average of three numbers entered by the user using integer variables.
  2. Create a program that converts Celsius to Fahrenheit and vice versa, using floating-point variables.
  3. Write a program that declares and initializes an array of 10 integers, then finds and prints the maximum value in the array.
  4. Write a program that declares and initializes two character arrays (strings) containing the names of two students. Compare their lengths and print the longer name.
  5. Write a program that uses pointers to swap the values of two integer variables without using a temporary variable.
  6. Write a program that dynamically allocates memory for an array of integers, reads user input into it, calculates the sum of even numbers, and frees the allocated memory when done.
  7. Write a program that defines a structure to represent a student (name, age, and GPA), creates an array of 5 students, reads user input to fill the array, sorts the students by age, and prints the sorted list.
  8. Write a program that uses pointers to implement a simple linked list data structure with integer nodes, inserts a new node at the end of the list, and traverses the list to print its contents.

FAQ

  1. Why should I initialize variables? Initializing variables helps prevent unpredictable behavior by ensuring that they contain meaningful values from the start.
  2. What happens if I use an integer variable for a decimal number? Using an integer variable for a decimal number will result in truncation, as integers can only store whole numbers.
  3. Why do I need to include header files in my C programs? Header files contain function prototypes and constant definitions that are necessary for your program to compile correctly.
  4. What is the difference between local and global variables in C? Local variables are declared within functions and only accessible within that function, while global variables are declared outside of any function and can be accessed from anywhere in the program.
  5. Why should I free dynamically allocated memory when it's no longer needed? Freeing dynamically allocated memory helps prevent memory leaks, which can cause your program to consume excessive resources or crash unexpectedly.