C Variables
In this page:
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
#include <stdio.h>
int main() {
int age;
age = 25;
printf("%d", age);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int age = 25;
printf("%d", age);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int x;
x = 5 + 3;
printf("%d", x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int a = 1, b = 2, c = 3;
printf("%d %d %d", a, b, c);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int counter = 100;
void show() {
printf("%d", counter);
}
int main() {
show();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- C Introduction
- C History & Features
- C Environment Setup
- C First Program
- C Syntax & Structure
- C Statements
- C Comments
- C Keywords & Identifiers
- C Data Types
- C Character Data Type
- C Numeric Data Types
- C Decimal (Floating-Point) Numbers
- C sizeof Operator
- C Extended Data Types
- C Type Conversion
- C Booleans
- C Variables
- C Changing Variable Values
- C Multiple Variables
- C Constants
- C Fixed-Width Integers