Skip to main content
Browse topics

Variables and Constants in C

2 min read Updated May 29, 2025
Share

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

c
data_type variable_name;
data_type variable_name = initial_value;

Examples:

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

Assigning and Updating Values

c
#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

plaintext
x = 18

Constants with const

The const keyword prevents modification after initialization:

c
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:

c
#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

c
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

Common Mistakes

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