What is Const

beginner c++11

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 declare function parameters as const as well. The function will not be able to mutate the parameters, which is useful if it is a reference.

#include <string>
#include <iostream>

void print_name(const std::string& name) {
  std::cout << name << "\n";
}

int main() {
  std::string name = "Rainier";
  print_name(name);
}
Rainier

For more C++ By Example, click here.