Course contentsShow
← C
Lesson 75 of 1,2192. Variables and TypesFree lesson

The syntax of a declaration

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;

  1. The Type: This tells the computer how much memory to grab. Are you storing a whole number? A decimal? A single letter?
  2. 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.
  3. 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" (like my_variable).
  • Start with a letter: You can use numbers inside the name, but never at the start (e.g., player1 is fine, but 1player will cause an error).
  • Case sensitivity: To C, Score and score are 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.