Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Const Usage Explanation

Tags:

c++

constants

const int* const Method3(const int* const&) const; 

Can someone explain the usage of each of the const?

like image 585
RoR Avatar asked Apr 08 '11 17:04

RoR


People also ask

What is use of const in C?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

What is the benefit of using const?

The const keyword allows you to specify whether or not a variable is modifiable. You can use const to prevent modifications to variables and const pointers and const references prevent changing the data pointed to (or referenced).

When to use #define vs const?

The difference is that #define is processed by the preprocessor doing what amounts to simple text replacement. Const values defined like this are not visible for the actual compiler, while a variable defined with the const modifier is an actual typed "variable" (well not really that variable).

What is the use of const statement?

The Const statement can declare the data type of a variable. You can specify any data type or the name of an enumeration.


1 Answers

It's easier to understand if you rewrite that as the completely equivalent

// v───v───v───v───v───v───v───v───v───v───v───v─┬┐ //                                               ││ //  v──#1    v─#2             v──#3    v─#4      #5    int const * const Method3(int const * const&) const; 

then read it from right to left.

#5 says that the entire function declaration to the left is const, which implies that this is necessarily a member function rather than a free function.

#4 says that the pointer to the left is const (may not be changed to point to a different address).

#3 says that the int to the left is const (may not be changed to have a different value).

#2 says that the pointer to the left is const.

#1 says that the int to the left is const.

Putting it all together, you can read this as a const member function named Method3 that takes a reference to a const pointer to an int const (or a const int, if you prefer) and returns a const pointer to an int const (const int).

(N.b. #2 is entirely superfluous.)

like image 79
ildjarn Avatar answered Nov 11 '22 20:11

ildjarn