Variables in C

This tutorial will help you learn about variables in C. You will find out what they are, their types, and how to use them. You will also learn where you can use a variable (scope) and how long it stays in memory (lifetime). Understanding variables helps with memory management. Real-world examples will make the concept clear.

Contents:

  1. What are Variables in C?
  2. Declaring and Initializing Variables in C
  3. Variable Naming Rules in C
  4. Conventions for Naming Variables in C
  5. Types of Variables in C
  6. Local Variables in C
  7. Global Variables in C
  8. Static Variables in C
  9. Automatic Variables in C
  10. External Variables (extern) in C
  11. Register Variables in C
  12. Constants vs Variables in C
  13. Best Practices for Using Variables in C
  14. FAQs on Variables in C

What are Variables in C?

In C programming, a variable is a name given to a memory location where data is stored. Variables act as placeholders for values that may change during the execution of a program. They play a crucial role in handling and processing data efficiently.

Declaring and Initializing Variables in C

In C programming, you must declare a variable before using it. This tells the compiler what type of data it will store and sets aside memory for it. Initialization means giving the variable a value when you declare it.

1. Declaring Variables

advertisement

In C, declaring a variable means specifying its type and giving it a name.

Syntax:

data_type variable_name;

Example:

Free 30-Day Python Certification Bootcamp is Live. Join Now!
int score;       // Declares an integer variable
float percentage; // Declares a float variable
char grade;      // Declares a character variable

2. Initializing Variables

A variable can be assigned an initial value at the time of declaration.

Syntax:

data_type variable_name = value;

Example:

int score = 95;        // Initializing an integer variable
float percentage = 88.5; // Initializing a float variable
char grade = 'A';      // Initializing a character variable

3. Multiple Variable Declarations and Initializations

You can declare multiple variables of the same type in a single line, optionally initializing them.

Example:

advertisement
int score, time, points;         // Declaring multiple variables
float x = 1.5, y = 2.5; // Declaring and initializing multiple variables

Example of Declaration and Initialization:

#include <stdio.h>
 
int main()
{
    int quizScore = 85;    // Declaration and Initialization
    float percentage = 90.5;
    char grade = 'A';
 
    printf("Quiz Score: %d\n", quizScore);
    printf("Percentage: %.2f%%\n", percentage);
    printf("Grade: %c\n", grade);
 
    return 0;
}

Output:

Quiz Score: 85
Percentage: 90.50%
Grade: A

This C program shows how to declare, initialize, and print variables. It creates an int (quizScore), a float (percentage), and a char (grade). Each variable stores a value. The printf function displays them using format specifiers: %d for integers, %.2f for floats (with two decimal places), and %c for characters. The %% prints the percentage symbol. The program runs and prints the values correctly.

Variable Naming Rules in C

In C, variable names must follow specific rules enforced by the compiler. Breaking these rules results in syntax errors. Below are the fundamental naming rules for variables in C.

1. Start with a Letter or Underscore: A variable name must begin with a letter (A-Z or a-z) or an underscore (_).

  • Valid: count, _score, value123
  • Invalid: 123value, #price

2. Cannot Use Keywords: C has reserved words (keywords) that cannot be used as variable names.

  • Valid: int1, float_value
  • Invalid: int, float, return, while

3. No Special Characters or Spaces: Variable names cannot contain special characters like @, #, $, %, etc. Spaces are not allowed.

  • Valid: student_marks, count2, max_value
  • Invalid: total$cost, my-variable, first name

4.Case Sensitivity: C is case-sensitive, so score and Score are treated as different variables.

int score = 50;
int Score = 100;

5. No Digits at the Beginning: Digits are allowed in variable names but cannot be the first character.

  • Valid: marks1, var123
  • Invalid: 123var, 1score

6. Length of Variable Names: Although C allows long variable names, it is best to keep names within 31 characters for portability.

int maximumStudentCount;

7. Use of Underscores: Variable names can contain underscores _ between characters.

int total_marks;

Conventions for Naming Variables in C

1. Use Meaningful and Descriptive Names: Choose names that clearly describe the variable’s purpose. Avoid single-character names except for loop counters (i, j, k).

  • Valid: int studentCount;
  • Invalid: int x;

2. Follow Camel Case or Snake Case Naming: Use camelCase or snake_case consistently.

  • Camel Case: int studentMarks;
  • Snake Case: int student_marks;

3. Use Uppercase for Constants (Macros): For constants or macros, use uppercase letters with underscores.

 #define MAX_STUDENTS 100 const int MIN_SCORE = 50;

4. Prefix Boolean Variables with “is”, “has”, or “can”: Boolean variables should indicate a condition or state.

  • Valid: int isPassed;
  • Valid: int hasAccess;

5. Use Singular Names for Single Variables and Plural Names for Arrays

  • Valid: int studentAge;
  • Valid: int studentAges[50];

6. Avoid Abbreviations (Unless Well-Known): Use full, clear names instead of vague abbreviations.

  • Valid: int totalMarks;
  • Invalid: int tm; // Unclear abbreviation

7. Avoid Using Underscores: For local variables, prefer camelCase. Use underscores for global variables or constants.

 int totalMarks; // Local variable

8. Consistency in Naming Style: Maintain a consistent style throughout the program.

  • Valid: int studentMarks;
  • Valid: float totalFee;

Types of Variables in C

In C Programming, variables are classified based on their scope, storage duration, and lifetime. Below are the main types:

  • Local Variables
  • Global Variables
  • Static Variables
  • Automatic Variables
  • External Variables (extern)
  • Register Variables

Local Variables in C

Local variables are declared inside a function or a block in C and can only be accessed within that function or block. Their scope is limited to the block where they are defined, and they cease to exist once the control leaves the block.

Characteristics of Local Variables:

  • Declared inside a function or block.
  • Accessible only within the same function or block.
  • Stored in the stack memory.
  • Memory is allocated when the function is called and deallocated when the function exits.
  • Cannot be accessed by other functions in the program.

Syntax:

return_type function_name()
{
    data_type variable_name;  // Local variable
    // Statements
}

Example:

#include <stdio.h>
 
void display()
{
    int marks = 85;  // Local variable
    printf("Marks inside display(): %d\n", marks);
}
 
int main()
{
    display();
 
    // Trying to access marks here will result in an error
    // printf("%d", marks);  // Error: marks is not accessible here
 
    int score = 90;  // Local variable for main()
    printf("Score inside main(): %d\n", score);
 
    return 0;
}

Output:

Marks inside display(): 85
Score inside main(): 90

This program shows local variables and their scope. The display() function has a variable marks, which can only be used inside that function. In main(), another variable score is declared and printed. Since marks belongs to display(), it cannot be used in main(). This helps keep variables separate and avoids errors.

Global Variables in C

Global variables in C are declared outside all functions, usually at the beginning of a program. They can be accessed and modified by any function within the same program.

Characteristics:

  • Declared outside any function.
  • Accessible from any function in the program.
  • Retains its value throughout the program.
  • Stored in the data segment of memory.

Syntax:

data_type variable_name;  // Global variable
 
int main()
{
    // Code
}
 
return_type function_name() {
    // Code can access global variable
}

Example:

#include <stdio.h>
 
// Global variable to store Sanfoundry score
int score = 90;
 
// Function to display the quiz score
void displayScore() {
    printf("Sanfoundry Quiz Score: %d\n", score);
}
 
// Function to update the score
void updateScore() {
    score += 10;
    printf("Updated Sanfoundry Quiz Score: %d\n", score);
}
 
int main() {
    displayScore();    // Display initial score
    updateScore();     // Update and display new score
    displayScore();    // Display updated score
    return 0;
}

Output:

Sanfoundry Quiz Score: 90
Updated Sanfoundry Quiz Score: 100
Sanfoundry Quiz Score: 100

This program shows global variables. The variable score is declared outside all functions, so every function can use it. The displayScore() function shows the score, and updateScore() adds 10 to it. In main(), the program first prints the score, then updates it, and prints it again. Since score is global, all functions can change it.

Static Variables in C

A static variable in C retains its value between multiple function calls. It is initialized only once and maintains its value even after the function exits.

Characteristics:

  • Memory allocated only once in the data segment.
  • Maintains its value between multiple calls.
  • Initialized only once, default value is 0 if uninitialized.

Syntax:

static data_type variable_name = value;

Example:

#include <stdio.h>
 
// Function to count Sanfoundry quiz attempts
void sanfoundryAttempt() {
    static int attempt = 0;  // Static variable
    attempt++;
    printf("Sanfoundry Quiz Attempt: %d\n", attempt);
}
 
int main() {
    sanfoundryAttempt();  // 1st attempt
    sanfoundryAttempt();  // 2nd attempt
    sanfoundryAttempt();  // 3rd attempt
    return 0;
}

Output:

Sanfoundry Quiz Attempt: 1
Sanfoundry Quiz Attempt: 2
Sanfoundry Quiz Attempt: 3

This program shows static variables. The variable attempt is static, so it keeps its value even after the function ends. Each time sanfoundryAttempt() runs, attempt increases by 1. In main(), calling the function three times makes the count go up. Normal variables reset each time, but static variables remember their value.

Automatic Variables in C

An automatic variable in C is a variable that is declared inside a function or a block and is automatically created when the function is invoked and destroyed when the function exits.

Characteristics:

  • Default storage class for variables.
  • Scope is local to the block or function where it is defined.
  • Memory allocated on the stack.
  • Automatically initialized with garbage value if not explicitly initialized.

Syntax:

auto data_type variable_name = value;  // 'auto' keyword is optional

Note: Since auto is the default, it is usually omitted.

Example:

#include <stdio.h>
 
void sanfoundryQuiz() {
    auto int score = 90;  // Automatic variable
    printf("Sanfoundry Quiz Score: %d\n", score);
}
 
int main() {
    sanfoundryQuiz();
    // score is not accessible here
    return 0;
}

Output:

Sanfoundry Quiz Score: 90

This program shows automatic variables. The function sanfoundryQuiz() creates the variable score when it runs and deletes it when it ends. Calling sanfoundryQuiz() in main() prints the score, but main() cannot use score because it exists only inside the function. In C, local variables are auto by default.

External Variables (extern) in C

An external variable in C is a variable that is declared outside of any function or block, making it global and accessible across multiple files or functions.

Characteristics:

  • Declared outside any function, typically at the top of the file.
  • Accessible to all functions within the file.
  • To use it in another file, it is declared with the extern keyword.

Syntax:

extern data_type variable_name;  // Declaration

Example:

File 1: sanfoundry.c

#include <stdio.h>
 
int sanfoundryScore = 85;  // External variable
 
void displayScore() {
    printf("Sanfoundry Quiz Score: %d\n", sanfoundryScore);
}

File 2: main.c

#include <stdio.h>
 
extern int sanfoundryScore;  // External variable declaration
 
void displayScore();  // Function prototype
 
int main() {
    displayScore();
    sanfoundryScore = 95;  // Modifying the external variable
    printf("Updated Sanfoundry Score: %d\n", sanfoundryScore);
    return 0;
}

Output:

Sanfoundry Quiz Score: 85
Updated Sanfoundry Score: 95

Register Variables in C

A register variable is a type of variable that is stored in the CPU register rather than in the main memory (RAM). It is declared using the register keyword.

Characteristics:

  • Stores frequently accessed data for faster access.
  • Used for optimization in time-critical operations.
  • The compiler may or may not honor the register request, depending on available CPU registers.
  • Cannot use the address-of operator (&) to get the address of a register variable.

Syntax:

register data_type variable_name;

Example:

#include <stdio.h>
 
int main() {
    register int sanfoundryMarks = 90;  // Declaring a register variable
 
    for (register int i = 0; i < 3; ++i) {  // Loop variable in register
        printf("Sanfoundry Marks: %d\n", sanfoundryMarks);
    }
 
    return 0;
}

Output:

Sanfoundry Marks: 90
Sanfoundry Marks: 90
Sanfoundry Marks: 90

Constants vs Variables in C

Here is a comparison table for Constants vs Variables in C:

Feature Constants Variables
Definition Fixed values that do not change during execution. Data storage locations whose values can change.
Declaration Declared using const keyword or #define. Declared using data types like int, float, char, etc.
Modification Cannot be modified after declaration. Can be updated during program execution.
Memory Usage Stored in read-only memory or replaced at compile time. Stored in RAM and can be modified.
Scope Follows the scope where declared but remains unchanged. Scope can be local or global, and values may change.
Lifespan Exists throughout program execution if defined globally. Exists only within its scope and may change multiple times.
Examples const int MAX = 100; or #define PI 3.14 int age = 25; or float price = 99.99;
Use Case Used for fixed values like mathematical constants. Used for dynamic data like user input and calculations.

Best Practices for Using Variables in C

  • Use clear and meaningful names instead of vague or single-character names.
  • Follow naming conventions like camelCase or snake_case, and avoid starting with numbers or special characters.
  • Declare and initialize variables at the same time to prevent garbage values.
  • Use const for fixed values to prevent accidental changes.
  • Select the correct data type to optimize memory and avoid data loss.
  • Reduce global variables by using static for file-specific scope or passing values through functions.
  • Use enum instead of hardcoded numbers for better readability and maintainability.
  • Remove unused variables to save memory and avoid unnecessary compiler warnings.

FAQs on Variables in C

1. What is a variable in C?
A variable in C is a named storage location used to hold data that can change during program execution.

2. Can a variable name start with a number?
No, variable names cannot start with a number. For example, 1stValue is invalid, but firstValue is valid.

3. What is the scope of a variable in C?

  • Local Scope – Variable is accessible only within the function/block where it is declared.
  • Global Scope – Variable is accessible throughout the program.
  • Block Scope – Variable is limited to a {} block where it is declared.

4. Can a variable be declared multiple times in C?
Yes, but only if it’s declared inside different scopes. Re-declaring the same variable in the same scope will cause an error.

5. What is the default value of an uninitialized variable?
Uninitialized variables in C contain garbage values (random memory content). Always initialize variables before use.

6. What is the lifetime of a static variable?
A static variable retains its value throughout the program’s execution, even if declared inside a function.

Key Points to Remember

Here is the list of key points we need to remember about “Variables in C”.

  • A variable holds data and can change while the program runs.
  • The name of a variable must start with a letter or an underscore. It cannot have spaces or special symbols. It is case-sensitive, so uppercase and lowercase letters mean different things.
  • Local variables exist only inside the function where they are created. They disappear when the function ends.
  • Global variables exist outside functions. Any part of the program can use them, and they keep their value until the program stops.
  • Static variables keep their value even after the function ends. The program creates them once and remembers their last value when the function runs again.
  • Automatic variables exist only when the function runs and disappear when it ends.
  • External variables appear in one file but work in another. They help share data across files in big programs.
  • Register variables store data in the CPU for faster access. The computer may not use a register if none are available.
  • Constants store fixed values that never change. They help keep important numbers like mathematical values.
  • Good practices include using clear names, initializing variables before use, picking the right data type, and limiting global variables.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.