Variables
7 min · C++
Store values in named, typed boxes called variables.
Enemy 1 of 5
Declaring and printing a variable
A variable is a named spot in memory where your program can stash a value and come back to it later. Instead of writing the same literal text or number over and over, you give it a name once and then refer to that name everywhere you need it, and if the value needs to change, you only change it in one place.
C++ is a statically typed language, which means every variable has a fixed type decided when you write the code, and that type never changes for the life of the variable. This is different from languages like Python or JavaScript, where a variable can hold a number one moment and text the next. In C++, once you declare something as an int, it can only ever hold whole numbers.
To create a variable you write the type, then the name, then an equals sign, then the value: string name = "Ada";. Text values use the string type (make sure #include <string> is available, though <iostream> often pulls it in indirectly), and whole numbers use int.
Once declared, you use the variable's name anywhere you'd otherwise use its value, including inside cout <<. This is the whole point: name = "Ada" now means the same thing as "Ada" until you reassign it.
A common early mistake is forgetting the type when declaring a variable, or trying to use a variable before it's declared. C++ reads your file top-to-bottom within a function, so a variable only exists starting from the line where you declare it.
Loading editor...