How to Declare Variables
beginner
c++11
In C++ every variable has its own type. There are built-in types such as int
, float
, and bool
and standard library types such as std::string
, std::map
, and std::vector
.
You can also declare your own types. The type of a variable cannot change
after it has been declared, an int
will always be an int
and a std::string
will be a std::string
.
Variables are mutable by default in C++, meaning the value of a variable can change
after it has been declared.
#include <string> #include <iostream> int main() { int x = 5; std::string name = "Baker"; std::cout << x << " " << name << "\n"; x = 40 + 2; name = "Rainier"; std::cout << x << " " << name << "\n"; }
5 Baker 42 Rainier
Variables in C++ are mutable, meaning they can change their values over time.
To declare a variable as immutable, or unchanging, in C++ we use const
.
#include <string> #include <iostream> int main() { const int x = 42; const std::string name = "Rainier"; std::cout << x << " " << name << "\n"; }
42 Rainier
You can use the keyword auto
to let the compiler
infer the type of a variable for you, but it will still always be the type the
compiler infers. You can still declare auto
variables as const
.
Be careful with strings! The type of characters in quotes ("like this"
)
is const char*
not std::string
.
#include <string> #include <iostream> int main() { auto x = 5; // int auto name = "Baker"; // const char* auto place = std::string{"Washington"}; // std::string const auto answer = 42; // const int std::cout << x << " " << name << " " << place << " " << answer << "\n"; x = 40 + 2; // still int name = "Rainier"; // still const char* place.append(", USA"); // still std::string std::cout << x << " " << name << " " << place << " " << answer << "\n"; }
5 Baker Washington 42 42 Rainier Washington, USA 42