How to Declare Variables in C: Syntax and Examples
In C, you declare a variable by specifying its
type followed by the variable name and ending with a semicolon, like int age;. This tells the computer to reserve space for that variable type and name.Syntax
To declare a variable in C, you write the data type first, then the variable name, and finish with a semicolon. The data type tells the computer what kind of value the variable will hold, such as numbers or characters.
type: The kind of data (e.g.,int,float,char).variable_name: The name you choose to identify the variable.;: Marks the end of the declaration.
c
type variable_name;Example
This example shows how to declare different types of variables and assign values to them. It then prints the values to the screen.
c
#include <stdio.h> int main() { int age = 25; // Integer variable float height = 5.9f; // Floating-point variable char grade = 'A'; // Character variable printf("Age: %d\n", age); printf("Height: %.1f\n", height); printf("Grade: %c\n", grade); return 0; }
Output
Age: 25
Height: 5.9
Grade: A
Common Pitfalls
Some common mistakes when declaring variables in C include:
- Forgetting the semicolon
;at the end of the declaration. - Using invalid variable names (like starting with a number or using spaces).
- Not matching the variable type with the value assigned.
- Declaring variables without initializing them and then using them before assigning a value.
c
#include <stdio.h> int main() { // Wrong: missing semicolon // int number // Wrong: invalid variable name // int 2ndNumber; // Wrong: assigning wrong type // int count = 3.5; // Right way: int number; int secondNumber; int count = 3; number = 10; secondNumber = 20; printf("Number: %d, Second Number: %d, Count: %d\n", number, secondNumber, count); return 0; }
Output
Number: 10, Second Number: 20, Count: 3
Quick Reference
| Component | Description | Example |
|---|---|---|
| Data type | Type of data stored | int, float, char |
| Variable name | Name to identify variable | age, height, grade |
| Semicolon | Ends the declaration | ; |
| Initialization | Assigning initial value | int age = 25; |
Key Takeaways
Declare variables by writing the type, then the name, ending with a semicolon.
Choose valid variable names starting with letters or underscore, no spaces or special characters.
Initialize variables to avoid using undefined values.
Match the variable type with the kind of data you want to store.
Always end declarations with a semicolon to avoid syntax errors.