Jump to content
  • Advertisement
Sign in to follow this  
subflood

constants vs. literals

This topic is 4876 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I'm not sure of the difference between a constant and a literal. I tried searching for it on google but the sites I was led to oly confused me more. Can anyone give me a simple explenation of a constant and a literal?

Share this post


Link to post
Share on other sites
Advertisement
Well, a constant generally refers to a variable or identifier that stands as a placeholder for a particular value. Once set, a constant's value cannot be changed.

Example (C++):

const int myConst = 5;
myConst = 20; //Compiler Error, can't set a constant
printf("I have %i fingers.", myConst); //prints "I have 5 fingers."


A literal, however, is where you have the value directly in code.

Example (C++):

return 9; //9 is a literal.

Share this post


Link to post
Share on other sites
A "literal" is a value given in plaintext in a program. Consider the following code:


int i = 7;
const double PI = 3.14;
printf("Hello, world!\n");



In this sample, there are three literals: 7, 3.14, and "Hello, world!". C++ has support for boolean literals (true and false), number literals, and string literals. These values are extracted directly from the code.

The term "constant" is considerably more nebulous, but generally refers to any value that does not change. Thus, PI would be considered a constant.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!