← Back to C Course | Chapter 1: Introduction & Basics | Lesson 17 of 21

C Variables

Variable Declaration

Declaring a variable tells the compiler to reserve a block of memory of the right size for that data type, and gives that memory a name you can refer to -- but the memory's contents are undefined until you actually assign a value.

Example: Variable Declaration

c
#include <stdio.h>
int main() {
	int age;
	age = 25;
	printf("%d", age);
	return 0;
}

Variable Initialization

Initializing a variable at the same time you declare it (int age = 25;) avoids the risk of accidentally reading garbage leftover memory, which is what happens if you try to use a variable's value before ever assigning one.

Example: Variable Initialization

c
#include <stdio.h>
int main() {
	int age = 25;
	printf("%d", age);
	return 0;
}

Lvalue and Rvalue

An lvalue is something with an addressable memory location (the left side of an assignment, like a variable), while an rvalue is a value that doesn't necessarily have a persistent address (like a literal number or the right side of an expression).

Example: Lvalue and Rvalue

c
#include <stdio.h>
int main() {
	int x;
	x = 5 + 3;
	printf("%d", x);
	return 0;
}

Multiple Variables

Declaring int a, b, c; creates three separate int variables in one line, saving a bit of typing -- but each still needs its own explicit initialization, since grouping the declaration doesn't share a starting value between them.

Example: Multiple Variables

c
#include <stdio.h>
int main() {
	int a = 1, b = 2, c = 3;
	printf("%d %d %d", a, b, c);
	return 0;
}

Variable Scope

A variable declared inside a function only exists and is only accessible while that function is running; a variable declared outside every function (a global) persists for the program's entire lifetime and is visible everywhere.

Example: Variable Scope

c
#include <stdio.h>
int counter = 100;
void show() {
	printf("%d", counter);
}
int main() {
	show();
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.