answersLogoWhite

0

Variables are not constant. If they were constant they would be constant. For example, time is a variable in many graphs. Were it to be constant it would mean that time stopped.

In programming such as C++ you often make a constant variable. The term variable refers to a usable instance of a type such as an integer. Making it constant means that it is unchangable but you can still use in the same manner as a variable. It is good practice to use constant variables rather than writing the values directly in the code because if the constant value changes it only needs to be changed in one place. For example:

without constant variable:

if (screenWidth > 200) {

lineEnd = 200;

}

drawLine(0, lineEnd);

with constant variable:

const int MAX_SCREEN_WIDTH = 200;

if (screenWidth > MAX_SCREEN_WIDTH) {

lineEnd = MAX_SCREEN_WIDTH;

}

drawLine(0, lineEnd);

In practice the value may be spread over many files and a search for 200 may find many other results that may be the wrong value.

Constant variables also help indicate the intention of the code without needing a comment. In the above example, the 200 does not indicate that it is the maximum screen width.

Making the variable constant means that the compiler will show an error if you try to change it.

MAX_SCREEN_WIDTH = 400; // will cause error

It is common practice to use uppercase letters to indicate a constant variable.

User Avatar

Wiki User

14y ago

Still curious? Ask our experts.

Chat with our AI personalities

DevinDevin
I've poured enough drinks to know that people don't always want advice—they just want to talk.
Chat with Devin
ViviVivi
Your ride-or-die bestie who's seen you through every high and low.
Chat with Vivi
MaxineMaxine
I respect you enough to keep it real.
Chat with Maxine

Add your answer:

Earn +20 pts
Q: Why does variables need to be constant?
Write your answer...
Submit
Still have questions?
magnify glass
imp