Home C C Variables tutorial with code examples

C Variables tutorial with code examples

In C programming, variables are used to store data that can be used and manipulated throughout a program.

A variable has a specific data type, a name, and it occupies a certain amount of memory to store a value.

1. Declaring Variables in C

To declare a variable, you specify the data type followed by the variable name. Optionally, you can also initialize the variable with a value.

Syntax:

data_type variable_name;

Example:

#include <stdio.h>

int main() {
    int age; // Declares an integer variable named 'age'
    age = 25; // Assigns a value to 'age'
    printf("Age: %d\n", age); // Prints the value of 'age'

    return 0;
}

In this example:

  • int is the data type.
  • age is the variable name.
  • The value 25 is assigned to age.

2. Initializing Variables

You can initialize variables at the time of declaration by assigning them a value directly.

#include <stdio.h>

int main() {
    int age = 25; // Declares and initializes 'age'
    float height = 5.9; // Declares and initializes 'height'
    char initial = 'A'; // Declares and initializes 'initial'

    printf("Age: %d\n", age);
    printf("Height: %.1f\n", height);
    printf("Initial: %c\n", initial);

    return 0;
}

3. Types of Variables

C supports different types of variables based on scope and lifespan:

  • Local Variables: Declared within a function, only accessible within that function.
  • Global Variables: Declared outside any function, accessible from any function in the program.
  • Static Variables: Retain their value between function calls, have a limited scope.
  • Automatic Variables: Default type for local variables, automatically destroyed when a function exits.

Example: Local vs. Global Variables

#include <stdio.h>

int globalVar = 10; // Global variable

void display() {
    int localVar = 5; // Local variable
    printf("Local variable: %d\n", localVar);
    printf("Global variable: %d\n", globalVar);
}

int main() {
    display();
    printf("Global variable in main: %d\n", globalVar);

    return 0;
}

In this example:

  • globalVar is declared outside any function, making it accessible to both display and main.
  • localVar is declared within display, so it is only accessible within that function.

4. Static Variables

A static variable retains its value between function calls, unlike a regular local variable.

Example: Static Variable

#include <stdio.h>

void increment() {
    static int count = 0; // Static variable
    count++;
    printf("Count: %d\n", count);
}

int main() {
    increment(); // Count = 1
    increment(); // Count = 2
    increment(); // Count = 3

    return 0;
}

In this example:

  • count is a static variable, so it retains its value each time increment is called.

5. Variable Types and Memory Allocation

Each variable type in C occupies a certain amount of memory:

  • int: Usually 4 bytes
  • float: Usually 4 bytes
  • double: Usually 8 bytes
  • char: 1 byte

You can use the sizeof operator to determine the memory size of each variable type.

#include <stdio.h>

int main() {
    printf("Size of int: %lu bytes\n", sizeof(int));
    printf("Size of float: %lu bytes\n", sizeof(float));
    printf("Size of double: %lu bytes\n", sizeof(double));
    printf("Size of char: %lu byte\n", sizeof(char));

    return 0;
}

6. Constants

In addition to variables, C allows the use of constants, which are values that cannot be changed once defined.

  • Using const keyword: Declares a read-only variable.
  • Using #define preprocessor directive: Creates a constant macro.

Example: Constants

#include <stdio.h>

#define PI 3.14159 // PI is a constant using #define

int main() {
    const int age = 25; // 'age' is a constant integer

    printf("Constant PI: %.5f\n", PI);
    printf("Constant age: %d\n", age);

    // age = 30; // This line would cause an error because 'age' is constant

    return 0;
}

In this example:

  • #define is used to create a symbolic constant, PI.
  • const is used to create a constant integer age.

7. Variable Naming Rules and Conventions

  • Rules: Variable names in C must start with a letter or underscore, followed by letters, numbers, or underscores. They are case-sensitive.
  • Conventions: Use meaningful names, like age or totalCount. Avoid generic names like x or y unless their purpose is clear.

Example: Naming Variables

#include <stdio.h>

int main() {
    int age = 30; // Good: descriptive
    float height = 5.9; // Good: descriptive

    // int 2count = 5; // Error: Cannot start with a number
    // int my-variable = 10; // Error: Hyphens are not allowed

    return 0;
}

In this example:

  • Valid variable names follow naming conventions, while invalid names violate C’s syntax rules.

8. Scope and Lifetime of Variables

  • Scope: Defines where a variable can be accessed. Local variables are limited to the function they are declared in, while global variables are accessible throughout the program.
  • Lifetime: Defines how long a variable exists in memory. Local variables exist only during function execution, while global variables exist for the program’s duration.

Example: Scope and Lifetime

#include <stdio.h>

int globalVar = 10; // Global variable, exists for the entire program duration

void testFunction() {
    int localVar = 20; // Local variable, only exists during this function's execution
    printf("Local variable: %d\n", localVar);
}

int main() {
    testFunction();
    // printf("Local variable in main: %d\n", localVar); // Error: localVar is not accessible here
    printf("Global variable in main: %d\n", globalVar);

    return 0;
}

In this example:

  • globalVar has global scope and lifetime.
  • localVar has local scope and only exists within testFunction.

Summary Table

Type Description
Local Variables Declared within a function, accessible only in that function, destroyed after function exits
Global Variables Declared outside functions, accessible across the entire program, exists for program's duration
Static Variables Retain value between function calls, limited scope
Automatic Variables Default type for local variables, destroyed after function exits

9. Working with Variables: Putting It All Together

Here’s a complete example that brings together the different types of variables and concepts discussed.

#include <stdio.h>

int globalCounter = 0; // Global variable

void incrementCounter() {
    static int localCounter = 0; // Static variable, retains value between function calls
    localCounter++;
    globalCounter++;
    printf("Local counter: %d, Global counter: %d\n", localCounter, globalCounter);
}

int main() {
    const int maxCount = 5; // Constant variable

    for (int i = 0; i < maxCount; i++) {
        incrementCounter();
    }

    printf("Final global counter value: %d\n", globalCounter);

    return 0;
}

In this example:

  • Global variable globalCounter keeps a total count accessible by all functions.
  • Static variable localCounter keeps a count for each incrementCounter call and retains its value.
  • Constant variable maxCount is a read-only integer, limiting the loop to 5 iterations.

This tutorial covers the basics of declaring, initializing, and working with variables in C, along with best practices for managing scope, memory allocation, and variable names.

You may also like