C++ has two kinds of constants: literal, and symbolic.
Literal constants
Literal constants are literal numbers inserted into the code. They are constants because you can’t change their values.
int x = 5; // 5 is a literal constant
Literal constants can have suffixes that determine their types. Integer constants can have a u or U suffix that means they are unsigned. Integer constants can also have a l or L suffix, which means they are long integers. However, these suffixes are typically optional, as the compiler can usually tell from context what kind of constant you need.
unsigned int nValue = 5u; // unsigned constant long nValue2 = 5L; // long constant
By default, floating point literal constant have a type of double. To convert them into a float value, the f or F suffix can be used:
float fValue = 5.0f; // float constant
Floating point literal constants can also use an l or L suffix to make them long doubles.
Generally, it is a good idea to try to avoid using literal constants that aren’t 0 or 1. For more detail, you can review the section on magic numbers, and why they are a bad idea.
Symbolic constants
As you learned in a previous lesson, you can use the #define preprocessor directive in order to declare a symbolic constant:
#define YEN_PER_DOLLAR 122 int nYen = nDollars * YEN_PER_DOLLAR;
There are two major problems with symbolic constants declared using #define. First, because they are resolved by the preprocessor, which replaces the symbolic name with the defined value, #defined symbolic constants do not show up in the debugger. Thus, if you only saw the statement int nYen = nDollars * YEN_PER_DOLLAR;, you would have to go looking for the #define declaration in order to find out what value of YEN_PER_DOLLAR was used.
Second, #defined values always have global scope (which we’ll talk about in the section on local and global variables). This means a value #defined in one piece of code may have a naming conflict with a value #defined with the same name in another piece of code.
A better way to do symbolic constants is through use of the const keyword. Const variables must be assigned a value when declared, and then that value can not be changed. Here is the way the above snippet of code should be written:
const int nYenPerDollar = 122; int nYen = nDollars * nYenPerDollar;
Declaring a variable as const prevents us from inadvertently changing it’s value:
const int nYenPerDollar = 122; nYenPerDollar = 123; // compiler error!
Although a constant variable might seem like an oxymoron, they can be very useful in helping to document your code and avoid magic numbers. Some programmers prefer to use all upper-case names for const variables (to match the style of #defined values). However, we will use normal variable naming conventions, which is more common. Const variables act exactly like normal variables in every case except that they can not be assigned to.
2.9 — Hungarian Notation
|
Index
|
2.7 — Chars
|
2.9 — Hungarian Notation
Index
2.7 — Chars
Could you not #define nYenPerDollar in a header file which is included in the main source code?
This would eliminate the inconvenience of having to search for its place of definition and would also prevent the confict you mentioned.
– Just a thought. I’m completely new to C++ and object-oriented programming all together, just trying to get my head around how many different ways the same task can be completed in C++.
PS: I am loving this tutorial. I’m using it for m pre-University study. =D
You could #define nYenPerDollar in a header file, but as I mentioned in the tutorial, #define values don’t show up in the debugger, which can make them hard to debug, especially if you code uses them heavily. Since the concept of yen per dollar is a global concept (it’s going to remain constant throughout the program) the fact that all #define values are global isn’t much of a problem in this case.
Literal constants are literal numbers inserted into the code. They are constants because you can’t change their values.
int x = 5; // 5 is a literal constant
I don’t understand this, you can change 5 to 6, how is it unchangable?
If you use the number 6 instead of 5, you are using a different literal, not changing the value of a literal. In other words, literals are constants because the symbol 5 always has the value 5. You can’t change the symbol 5 to the value 6, or any other number.
Alex:
Ref.: it is a good idea to try to avoid using literal constants that aren’t 0 or 1.
So I should use only literal constants that are 0 or 1?¿? As for above.
Generally I only use the literal constant 0 — anything else is either defined as a #define value, a const int, or an enum.
[...] 2007 Prev/Next Posts « 2.8 — Constants | Home | 2.10 — Comprehensive quiz » Monday, June 11th, 2007 at 4:04 [...]
[...] 2007 Prev/Next Posts « 2.6 — Boolean Values | Home | 2.8 — Constants » Saturday, June 9th, 2007 at 7:07 [...]
Did constants apply through the whole file? Or what? :S I mean const values using the
keyword.
Const variables have the same scoping rules as normal variables. If you declare them globally, they apply though the whole file. If you declare them locally, they will die when they go out of scope. The only difference is that the value of a const variable can’t be changed after initialization.
from your previous lesson 2.4- integers
you said that “All integer variables except char are signed by default.”
but i am confusing from the above example of this lesson because the nValue variable is an integer type and it is signed by default. while the value of nValue variable is 5u and it is using a suffix of unsigned integer type.
can you please explain me why nValue become an integer signed variable while the value 5u is unsigned?
[ Just a mistake on my part. nValue should be an unsigned int. I fixed it in the example. -Alex ]
Alex,
In the sentence before the last snippet of code, you wrote “.. changing it’s value” it should be “its” in place of “it’s”.
no, it’s is correct, the ‘ shows ownership. Changing IT’S value involves ownership. it’s is correct.
No, “its” is the possessive form. “It’s” is a contraction for “it is”. It’s a very common typo, but you can tell its meaning from the context anyhow.
this is very nice tutorial..
i m not new to c++ also not proficient but getting good concepts from this tutorial
Alex,
How about const with respect to functions?
what if you intalize a const varible, but don’t assign it a value right away?
it doesnt work and gives an error :
error: uninitialized const ‘nYenPerDollar’
if you try to assign it later it says :
error: assignment of read-only variable ‘nYenPerDollar’
Any chance you’re going to put together a glossary of all the terms, possibly with links to the appropriate sections on the tutorial?
I have been working on one for myself as we go along if you want a copy thus far
I would love one Islanding, if you ever come about to reading this again.
jcorio92doughboy@sbcglobal.net
[...] 2.8 Constants [...]
Hi Alex,
I’m new to c++. My question may be dump to you but what’s the difference between “int = 5″ or “int == 5″.
there is no such thing like “int = 5″ or “int == 5?
“int” is a keyword used to define variables type
int nValue; // declaring nValue as an integer nValue = 5; // assigning value 5 to nValue nValue == 5; // check if nValue is 5, used in if statements // ex: if( nValue == 5 ) { cout << "nValue is equal to 5"; }thanks a lot dear.
The information is good here, but using “yen per dollar” as a constant is a terrible example. You don’t use something that changes multiple times a day as a constant! “yen per dollar” is best used as a variable!
Use something as an example that doesn’t change, like “centimeters per meter”, “inches per foot” or “pounds per kilogram”.
Hi.
I’d like to know which one is better:
const or #define.
Thanks in advance…
Both have their own uses. Read around to find out which one you want to use.
Does #define use up memory just as int does?
Yes it does. Why wouldn’t it?
What happen if we use ‘;’ after the #define? See below for example:
#include
#define MAX 100;
using namespace std;
main()
{
cout << MAX+2 << ' ' << 4+9;
}
cout dose not print the result of the 4+9! why?
It simply makes the semicolon part of the definition, meaning that using the ‘MAX’ would automatically end the statement.
Also, your code should give you a compiler error.
[...] KNOWLEDGE FOR BOTH PROGRAMS Float Data Type Constant Values Arrays For Loops Assignment Operators Basic [...]
Hi
Please let me know how memory is allocated in #define and const?
What is the difference?
[...] REQUIRED KNOWLEDGE FOR THIS SNIPPET Integer Arrays For Loops Constants [...]