The syntax of a declaration
What you'll learn: How to write a basic line of C code that tells the computer to set aside memory for a specific piece of data.
The Recipe for a Variable
In C, a variable doesn’t just appear out of thin air. Before you can use one, you must "declare" it. Think of a declaration as placing a reservation at a restaurant. You are telling the computer two things: what kind of "table" you need and what name you want to call it.
The syntax follows a strict, two-word pattern:
type name;
- The Type: This tells the computer how much memory to grab. Are you storing a whole number? A decimal? A single letter?
- The Name: This is the label you'll use to refer to that memory later. It should be descriptive so your code is easy to read.
- The Semicolon: In C, the semicolon (
;) is like a period at the end of a sentence. It tells the compiler, "I'm finished with this instruction."
A Concrete Example
Imagine you are building a simple game and you need to keep track of a player's score. Since a score is usually a whole number, we use the type int (short for integer).
int playerScore;
int healthPoints;
float playerSpeed;
In the first line, int is the type and playerScore is the name. The moment the computer sees this, it carves out a small slot in its memory large enough to hold an integer and slaps the label "playerScore" on it.
The Golden Rules of Naming
While you have freedom in naming your variables, C is picky about the details.
- No spaces: Use "camelCase" (like
myVariable) or "snake_case" (likemy_variable). - Start with a letter: You can use numbers inside the name, but never at the start (e.g.,
player1is fine, but1playerwill cause an error). - Case sensitivity: To C,
Scoreandscoreare two completely different boxes in memory.
By declaring a variable, you aren't putting a value in it yet; you are simply building the container. It’s an empty box with a label, sitting in the computer’s memory, waiting for you to give it something to hold.
Key takeaway
A declaration consists of a data type, a unique name, and a semicolon.