const identification

Const identification

Have a look at these 3 code snippets. Consider which variables should be declared const based on the information you can gain from the variable name.

int max_attempts = 5;
int attempts = 0;
int screen_width = get_screen_width();
int screen_height = get_screen_height();
std::string welcome_message = "Welcome to the Game!";
int welcome_message_length = welcome_message.length();

Hint

Variables that describe a property that should not change during the program execution should be declared const if they don't require a "setup" (multiple statements to set the value).

Answer

const int max_attempts = 5;
int attempts = 0;

attempts is a counting variable, so it should not be declared const. max_attempts should not change during the program execution.

const int screen_width = get_screen_width();
const int screen_height = get_screen_height();

screen_width and screen_height are both describing the dimensions of the screen, which should not change during the program execution.

const std::string welcome_message = "Welcome to the Game!";
const int welcome_message_length = welcome_message.length();

welcome_message is a constant string that should not change during the program execution. welcome_message_length is the length of the welcome_message string, which won't change during the program execution.

Questions