๐ŸŽ“ A1Learner
๐Ÿ”

C++ Variables

A variable is a name given to a stored value. The program can change that value while it runs.

Declare, assign, and print

The first line declares score as an int. The next line assigns 10, and a print line then shows the value.

#include <iostream>

int main() {
  int score;
  score = 10;
  std::cout << score << std::endl;
  return 0;
}

Two variables, one changed

Two lines declare first and second with starting values. A later line changes only second, and both values print.

#include <iostream>

int main() {
  int first = 3;
  int second = 4;
  second = 10;
  std::cout << first << std::endl;
  std::cout << second << std::endl;
  return 0;
}

Three variables on one line

One line declares three int variables and gives each one a value. The print line adds the three values and shows the sum.

#include <iostream>

int main() {
  int first = 2, second = 3, third = 4;
  std::cout << first + second + third << std::endl;
  return 0;
}

An undeclared name

This program prints a name that was never declared. The compiler refuses the program and reports the error line below.

#include <iostream>

int main() {
  int score = 10;
  std::cout << total << std::endl;
  return 0;
}

Example

#include <iostream>

int main() {
  int score = 90;
  int level = 3;
  std::cout << "Score: " << score << std::endl;
  std::cout << "Level: " << level << std::endl;
  return 0;
}

Key points

  • A type says what kind of value a variable holds.
  • To declare a variable means to create it in code.
  • Use int for a variable that holds whole numbers.
  • To assign a value means to set the value a variable holds.
  • A later line can assign a new value to a variable.
  • One line can declare three int variables, each with its own value.
  • Printing a variable shows its current value.

In this example, score holds 90 and level holds 3. The first print line shows the label Score beside 90. The second print line shows the label Level beside 3.

Note

A variable holds one value at a time.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

Which line declares an int variable and assigns it a value at once?