Lesson 24 +10 XP

Declaring Variables

Declaring Variables

In C++, we create a variable with one simple formula: a type, then a name, then a value.

The general form

type variableName = value;

Where type is one of the data types (like int or double), variableName is the name we choose, and = value gives it a starting value.

A few real examples

int myNum = 15;        // whole number
double myFloatNum = 5.99;   // number with a decimal
char myLetter = 'D';   // one single character
string myText = "Hello";    // a string of text
  • int myNum = 15; - an integer holding 15.
  • double myFloatNum = 5.99; - a decimal number.
  • char myLetter = 'D'; - one character, in single quotes.
  • string myText = "Hello"; - a word or sentence, in double quotes.

Reading it out loud

int myNum = 15; can be read as: "an integer variable named myNum, and put the value 15 in it." The order is always: type, name, value.

A good name is worth it

The name is up to us, so make it meaningful. int myNum is fine for learning, but in a real program int highScore = 100; tells you what the value means. A name like x saves no time and costs a lot of confusion later.

TL;DR

  • Declaration form: type variableName = value;.
  • int myNum = 15; stores a whole number.
  • double myFloatNum = 5.99; stores a decimal.
  • char myLetter = 'D'; stores one character in single quotes.
  • Always pick clear, meaningful names.