This question already has answers here:
C++ Const Usage Explanation
(12 answers)
Closed 7 years ago.
I'm new to using C++ to write enterprise software at my company and the usage of const in member functions has been quite confusing to me. For example, I have the following method:
string DAC::impulse_find(int i)
There will be no modification of the variable i. My code compiles perfectly when I use these three variants of adding const to the above method:
const string DAC::impulse_find(const int i) const
const string const DAC::impulse_find(const int i) const
string const DAC::impulse_find(const int i) const
So what exactly is the difference between these three? I looked at some past answers and say "It applies to whatever is to the left" but that is still confusing. Does it apply to anything, such as the name of the class as well?
There is no difference between
const std::string
std::string const
The order of const is irrelevant since you are not dealing with pointers.
Having many const as a qualifier doesn't make sense. Did you turn up the warning level on your compiler to maximum?
Edit 1: Pointers and Const
Since you are returning a copy of a variable the effectiveness of const is worthless. The original item from the function can't be modified because you are returning a copy.
Maybe you are confused with the pointer syntax, where the placement of const matters:
string const * const -- constant pointer to a constant (read-only string). Pointer cannot be modified.
string const * -- Mutable pointer to a constant (read-only) string. Pointer value can change.
string * const -- Constant pointer to a read/write string. Pointer value cannot be changed.
string * -- Mutable pointer to a read/write string. Pointer value can be changed.
The const for read-only data may be placed before or after the type:
const string *
string const *
Both of the above are equivalent.
All three version
const string …
const string const …
string const …
are identical.
The placement of const doesn't matter here. The duplicate const in the second version is redundant and your compiler should give a warning about it.
Moreover, the consts don't make sense here because the string is returned as a copy. Returning a const value brings you nothing (see KABoissonneault's comment), only references or pointers to const make sense as a return type.
Related
This question already has answers here:
What is the difference between const int*, const int * const, and int const *?
(23 answers)
Closed 6 years ago.
I am a beginner to c++. The below code snippet is taken from a program for parsing text input.
const int MAX_CHARS_PER_LINE = 512;
const int MAX_TOKENS_PER_LINE = 20;
const char* const DELIMITER = ",";
I couldn't find a reason for why the programmer used
const pointer
for variable DELIMITER, as he didn't use const pointer for other variables. Please clarify.
512 and 20 are constants of type int. Their values can be stored in objects (variables) of type int. There's no need for pointers.
A string literal like "," is not a simple scalar value. It's of type const char[2], an array of two chars. (const means read-only.)
Though arrays and pointers are very different things (and don't let anyone tell you otherwise!), arrays in C and C++ are most commonly manipulated via pointers to their elements. Thus a char* pointer can be used to, for example, traverse a string and provide access to each of its elements.
The extra const means that the pointer itself cannot be modified.
This question already has answers here:
Const correctness: const char const * const GetName const (//stuff);
(8 answers)
Closed 8 years ago.
I have a function with 3 const's in it:
const std::string at(const unsigned int index) const;
To my understanding, the parameter (const unsigned int index ) means that index will not be changed. What about the other two const's? Why are they there?
The const keywoard in C++ indicates that a particular object or variable is not modifiable. It can be used in various contexts:
Const variables
Declaring a variable as const inside of a function indicates that the variable will not be modified inside the function.
Const member functions
Declaring a member function as const, which is done by appending const to the end of the function prototype, indicates that the function is a "read-only" function that does not modify the object for which it is called.
The rule for const viability is that const-ness can be applied to a non-const variable or member function, but once applied it cannot be removed.
The first const says that the return type is const, the second const says the parameter is const, and the third const says that the function is a const function...
This question is actually a duplicate... follow this link
C++ Const Usage Explanation
const std::string at(const unsigned int index) const;
in this example, the first const from left side is a constant for return type, which means whatever value it will return that can be saved in a const variable only (even type casting is possible which will change the property of data).
second const as you said it is correct.
third const says that the function is constant function. that means inside that function you are not modifying any variables which will change the state of objects.
if you are modifying any class or global variable inside const function then compiler will throw error.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Declaring pointers; asterisk on the left or right of the space between the type and name?
I've always been wondering what's the exact correct position to put * and &. it seems that C++ is pretty tolerant about where to put these marks.
For example I've seem pointer and ampersand been put on both left and right of a keyword or in the middle of two keywords, but confusingly sometimes they seems to mean the same thing, especially when used together with const
void f1(structure_type const& parameter)
void f2(structure_type const ¶meter)
void f2(structure_type const *sptr);
void f2(structure_type const* sptr);
void f2(structure_type const * sptr);
The examples are not exhaustive. I see them everywhere while being declared or been passed to a function. Do they even mean the same thing? But I also see cases while putting * will affect which object being referred as a pointer (likely the case where * is in between two keywords).
EDITED:
int const *Constant
int const * Constant // this above two seem the same to me, both as pointer to a constant value
int const* Constant // EDIT: this one seems the same as above. instead of a constant pointer
const int * Constant // this is also a pointer to a constant value, but the word order changed while the pointer position stays the same, rather confusing.
int* const Constant
int * const Constant // instead, these two are constant pointers
So I concluded this:
T const* p; // pointer to const T
const T* p // seems same from above
T* const p; // const pointer to T
Still, this confused the hell out of me. Doesn't the compiler care about position and the spacing required for them?
Edit:
I want to know in general of the position matters. If yes in what cases.
White space matters only to the degree that it keeps tokens from running together and (for example) creating a single token, so (for example) int x is obviously different from intx.
When you're dealing with something like: int const*x;, whitespace on either size of the * makes absolutely no difference to the compiler at all.
The difference between a pointer to const int and const pointer to int depends on which side of the * the const is on.
int const *x; // pointer to const int
int *const x; // const pointer to int
The primary difference is readability when/if you define/declare multiple objects in the same declaration.
int* x, y;
int *x, y;
In the first, somebody might think that x and y are pointers to int -- but in fact, x is a pointer to an int, and y is an int. To some people's eyes, the second reflects that fact more accurately.
One way to prevent any misinterpretation is to only ever define one object at a time:
int *x;
int y;
For any of these, correct interpretation is fairly easy if you ignore whitespace entirely (except to tell you where one toke ends and another starts, so you know "const int" is two tokens) and read from right to left, reading * as "pointer to". For example: int volatile * const x; is read as "x is a const pointer to a volatile int".
int const *Constant
int const * Constant
int const* Constant
All of the above intend to declare a non constant pointer to a constant integer.
Simple rule:
If const follows after the * it applies to the pointer if not it applies to the pointed object. The spacing doesn't matter.
Both & and * placements in variable declaration are acceptable and only depends on your own flavour. They strictly mean the same thing, creating respectively a pointer and a reference.
However, the const keyword placement is primordial, as a int const* variable declares a constant pointer to a non-constant int, and const int* variable is a non-constant pointer to a constant int.
I have seen const used twice in the declaration of a static array before and now that I am creating my own static array I am wondering why const would be needed twice in some situations.
Does having an array of pointers make a difference?
a. static const TYPE name[5];
b. static const TYPE const name[5];
c. static const TYPE* name[5];
d. static const TYPE* const name[5];
My understanding is that b. is invalid, but if using const twice is valid, what is its purpose?
const TYPE* x;
Means that the thing that x points at is const.
TYPE* const x;
Means that the pointer x is const.
Combining the 2 you get:
const TYPE* const x;
Meaning the pointer and the thing pointed to are both const.
You can apply any cv-qualifier (const or volatile) to any type, including cv-qualified types -- yet not in the same declaration. However, they bind more strongly than any operator, in terms of precedence and can be applied on both sides of the qualified type:
// Let T by any type:
T const tr;
const T tl;
const T const tlr; // only in C
const const const const const T t5; // only in C
typedef const T CT;
CT const tcc; // fine, although CT was already const
declare exactly the same, a constant T. If T already has cv-qualifiers, this doesn't change the meaning of additional qualification.
Now, to the precedence; You can say "I want a pointer to a constant T":
const T (* tp);
which is usually written as
const T* tp;
because the const binds stronger than the * anyway. In the same pattern, you can define a variable that is "constant but points at a mutable T":
T (* const tp) = 0; // must be initialised, because tp is immutable
which is commonly written as
T* const tp = 0;
In the same vein the subscript operator [] is applied -- with the same precedence as in expressions.
In the first code block you have a redundant duplicate const in the second line, which has no effect. (In fact, good compilers will warn you about this.) You're declaring an array of 5 const TYPEs, that's it.
The second code block has two different scenarios: The first line makes an array of five mutable pointers to const TYPEs, while the latter makes an array of five constant pointers to const TYPEs.
Note that you must initialize an array of constants: Since you can't change the values later, it doesn't make sense to define them uninitialized.
Using const twice on a type is illegal in C++ 2003 but legal in C++ 2011 (see 7.1.6.1 [decl.type.cv] paragraph 1: "Redundant cv-qualifications are ignored."). When you used
static const TYPE const name[5];
you made TYPE constant twice. Note, however, that this declaration is illegal in C++ 2011, too, because you need initialize a const object when declaring it. The meaning of
const TYPE
and
TYPE const
is absolutely equivalent: In both cases you make the TYPE object constant. For consistency, I always put the const to the right because every except for the top-level type the const has to be put on the right side (well, unless some coding guideline mandates differently but I'm fighting silly coding guidelines).
When using pointers, thinks become different. There are two types involved: type pointed to type and the pointer. Each one of these can be made const separately:
TYPE const* ptr1(0); // non-const pointer to const TYPE
TYPE* const ptr2(0); // const pointer to non-const TYPE
TYPE const* const ptr3(0); // const pointer to const TYPE
The best way to figure out what is made const is to read the type declaration from right to left. Of course, this assumes to that const qualifiers are put into the right location. You can replace const by volatile or const volatile in the discussion above and the same reasoning applies.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between const int*, const int * const, and int const *?
I am trying to understand how const works in a function parameter. What is the difference between void function(int const *&i); and void function(const int *&i);? And I would appreciate if you gave an example of their implementation and of the usage of i.
They are the same, just read it from right to left:
First example: i is a reference to a pointer of a constant integer.
Second example: i is a reference to a pointer of an integer constant.
The placement of const only changes things on either side of the pointer. For example:
const int* i
means: i is a pointer to a constant integer
whereas int* const i
means: i is a constant pointer to an integer.
Those declarations are equivalent. For more info, see this page.
Best place for const correctness is the - C++ FAQ Lite
They're both the same.
It means a reference to a pointer to a const int.