user81993
user81993

Reputation: 6613

what is the second const doing in "const int const &someval"?

talking about a function parameter, for example:

void doSomething(const int const &someVal);

As far as I understand, the fist const indicates that the value will not be changed by the function, and the & indicates that the value should be passed by reference. But what does the second 'const' do?

Upvotes: 3

Views: 149

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

According to the C++ Standard (7.1.6.1 The cv-qualifiers)

1 There are two cv-qualifiers, const and volatile. Each cv-qualifier shall appear at most once in a cvqualifier- seq. If a cv-qualifier appears in a decl-specifier-seq, the init-declarator-list of the declaration shall not be empty. [ Note: 3.9.3 and 8.3.5 describe how cv-qualifiers affect object and function types. —end note ] Redundant cv-qualifications are ignored. [ Note: For example, these could be introduced by typedefs.—end note ]

So this declaration

void doSomething(const int const &someVal);

has a redundant const qualifier that is simply ignored.

The second const qualifier would have a sense if someVal would be declared as a reference to const pointer. For example

void doSomething(const int * const &someVal);

Upvotes: 2

Augustin Popa
Augustin Popa

Reputation: 1543

Both of these should work:

void doSomething(const int &someVal);

void doSomething(int const &someVal);

Using a second const doesn't add any functionality and the extra one should be removed. It's a good practice to keep the const to the left though for clarity as it stands out better.

Upvotes: 0

Related Questions