简体   繁体   中英

Difference between variable assigning and literal constant?

I am bit confused about assigning a value to variable and literal constants.

For example:

int age = 20;

age is a variable, and 20 is the value assigned to it.

And:

int AGE = 20; 

AGE is literal constant, 20 is the value assigned to it.

What is the difference? Will constants take the same two bytes in main memory as variables?

You are confused indeed:

 int age = 20;

assigns integer value 20 to a variable age .

int AGE = 20;

assigns integer value 20 to a variable AGE .

There's no difference.

 int AGE = 20; 

AGE is literal constant, 20 is the value assigned to it.

No, AGE is a variable, same as age (but with a different name).

To declare a constant:

const int AGE = 20;

To use a literal constant directly ( this is discouraged in modern C++ ):

#define AGE 20 // every time you use AGE, the literal "20" will be used instead

There is no difference in your case:

int age = 20;

is a variable named "age" with value 20.

int AGE = 20;

is a variable named "AGE" with value 20.

If you want to declare a constant with a specific type in your code using const prefix:

const int AGE = 20;

In other case, you can use the #define preprocessor:

#define AGE 20;

The difference between a variable and a constant (or literal constant) is that the constant, once defined, you cannot change its value.

AGE is literal constant, 20 is the value assigned to it.

Incorrect!

You cannot assign a value to a literal constant. The literal constant is the value assigned to the variable.

I got confused originally because my textbook and online resources give "int mynum = 20;" as an example of a literal constant and "int anum = 20;" as an example of a variable.

It wasn't until I read it over 100 times that I realized that both "mynum" and "anum" are variables whereas 20 is the literal constant.

Constant literals are like regular variables, occupy same size. The only difference is that the value of constant variable cannot be altered. We use the key word const to indicate a constant variable

const int AGE=20;

we capitalize the constant variable just to distinguish it from regular variables.

  int AGE = 20; 

AGE is literal constant, 20 is the value assigned to it.

AGE is just a variable name and 20 is a literal constant. More information http://www.cplusplus.com/doc/tutorial/constants/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM