Lesson 23 +10 XP

Variables

Variables

Before we write programs that do useful work, we need a way to store information. That's where variables come in.

What is a variable?

A variable is a named chunk of memory that stores a value. Think of it as a labeled box: the box has space inside, and what we put in the box is the value.

Declaring a variable

In C you declare a variable with a type, a name, and optionally a value:

int myNum = 15;
  • The type (int) says what kind of value the box can hold.
  • The name (myNum) is how we talk about the box in our code.
  • The = 15 puts a starting value inside.

More examples

int myNum = 15;             // whole number
float myFloatNum = 5.99;    // decimal number
char myLetter = 'D';        // one character

Why store values?

Almost everything a program does works on data. Instead of re-typing a value again and again, we store it once in a variable and use the name everywhere.

TL;DR

  • A variable is a named box of memory holding a value.
  • Declare with: type, name, value.
  • int myNum = 15; stores the whole number 15.
  • Variables let us reuse data anywhere in the program.