Skip to main content

Variables and Constants in C

2 min read Updated May 29, 2025
Share:
On this page (12sections)

Introduction

A variable is a named memory location that stores a value. A constant is a value that does not change during program execution. Understanding both is essential before writing any C program.

Declaring Variables

data_type variable_name;
data_type variable_name = initial_value;

Examples:

int count;
int total = 0;
float price = 19.99f;
char initial = 'T';

Assigning and Updating Values

#include <stdio.h>

int main(void) {
    int x = 10;
    x = x + 5;          /* x is now 15 */
    x += 3;             /* same as x = x + 3 */
    printf("x = %d\n", x);
    return 0;
}

Sample Output

x = 18

Constants with const

The const keyword prevents modification after initialization:

const float PI = 3.14159f;
const int MAX_STUDENTS = 100;

/* PI = 3.14;  ERROR — cannot assign to const variable */

Constants with #define

Preprocessor macros define symbolic constants before compilation:

#include <stdio.h>

#define PI 3.14159
#define MAX_SIZE 100

int main(void) {
    printf("PI = %.5f, MAX = %d\n", PI, MAX_SIZE);
    return 0;
}

See C Preprocessor Directives for more on #define and macros.

Multiple Variables in One Line

int a, b, c;
int x = 1, y = 2, z = 3;

Naming Rules

Variable names must follow C identifier rules — see C Identifiers. Use meaningful names like studentCount instead of x.

Best Practices

  • Initialize every variable before reading its value.
  • Use const for values that should never change (more type-safe than #define).
  • Use UPPER_CASE for macro constants (#define MAX 100).
  • Declare variables close to where they are first used.

Common Mistakes

  • Using a variable before initialization — leads to unpredictable output.
  • Confusing = (assignment) with == (comparison).
  • Redefining a macro or const name elsewhere in the program.

Continue learning with these related tutorials and programs:

Frequently Asked Questions

What is the difference between a variable and a constant?
A variable can change during program execution. A constant cannot be modified after initialization — use the const keyword or #define for fixed values.
Must I initialize variables in C?
Local variables are not auto-initialized — they contain garbage values until you assign one. Always initialize before use.

Related Tutorials

Search tutorials