cpp / beginner
Snippet
Konstanten mit const und constexpr
Konstanten sind Werte, die sich während der Programmausführung nicht ändern. Verwenden Sie const für Werte, die zur Laufzeit berechnet werden und sich nicht ändern. Verwenden Sie constexpr für Werte, die zur Kompilierzeit berechnet werden können - diese sind schneller, da sie berechnet werden, bevor das Programm läuft. Beide verhindern versehentliche Änderungen und machen Code-Absichten klarer.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>constexpr int DAYS_IN_WEEK = 7;constexpr float PI = 3.14159f;int main() {const int MAX_PLAYERS = 4;const std::string GAME_NAME = "Chess";std::cout << GAME_NAME << " allows " << MAX_PLAYERS << " players" << std::endl;std::cout << "Pi is approximately " << PI << std::endl;std::cout << "A week has " << DAYS_IN_WEEK << " days" << std::endl;// Cannot modify: MAX_PLAYERS = 5; // ERROR!// Cannot modify: PI = 3.14; // ERROR!return 0;}
Erklärung
1
constexpr int DAYS_IN_WEEK = 7;
Kompilierzeit-Konstante - berechnet bevor das Programm läuft
2
constexpr float PI = 3.14159f;
Mathematische Konstante, die zur Kompilierzeit berechnet wird
3
const int MAX_PLAYERS = 4;
Laufzeit-Konstante - Wert erst bekannt wenn Programm ausgeführt wird
4
const std::string GAME_NAME = "Chess";
const funktioniert mit jedem Typ einschließlich std::string
5
// Cannot modify: MAX_PLAYERS = 5; // ERROR!
Ein Versuch eine const-Variable zu ändern verursacht einen Kompilierfehler