Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ "const" keyword explanation

Tags:

c++

constants

When reading tutorials and code written in C++, I often stumble over the const keyword.

I see that it is used like the following:

const int x = 5; 

I know that this means that x is a constant variable and probably stored in read-only memory.

But what are

void myfunc( const char x ); 

and

int myfunc( ) const; 

?

like image 615
RajX Avatar asked Oct 31 '10 17:10

RajX


People also ask

What does const keyword do in C?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.

What is constant keyword in C with example?

A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc. There are different types of constants in C programming.

What is keyword constant explain it?

A global variable or static variable can be declared (or a symbol defined in assembly) with a keyword qualifier such as const , constant , or final , meaning that its value will be set at compile time and should not be changeable at runtime.

What is const * const in C?

const int* const is a constant pointer to constant integer This means that the variable being declared is a constant pointer pointing to a constant integer.


2 Answers

void myfunc(const char x); 

This means that the parameter x is a char whose value cannot be changed inside the function. For example:

void myfunc(const char x) {   char y = x;  // OK   x = y;       // failure - x is `const` } 

For the last one:

int myfunc() const; 

This is illegal unless it's inside a class declaration - const member functions prevent modification of any class member - const nonmember functions cannot be used. in this case the definition would be something like:

int myclass::myfunc() const {   // do stuff that leaves members unchanged } 

If you have specific class members that need to be modifiable in const member functions, you can declare them mutable. An example would be a member lock_guard that makes the class's const and non-const member functions threadsafe, but must change during its own internal operation.

like image 116
Steve Townsend Avatar answered Sep 30 '22 10:09

Steve Townsend


The first function example is more-or-less meaningless. More interesting one would be:

void myfunc( const char *x ); 

This tells the compiler that the contents of *x won't be modified. That is, within myfunc() you can't do something like:

strcpy(x, "foo"); 

The second example, on a C++ member function, means that the contents of the object won't be changed by the call.

So given:

class {   int x;   void myfunc() const; } 

someobj.myfunc() is not allowed to modify anything like:

x = 3; 
like image 41
Paul Roub Avatar answered Sep 30 '22 10:09

Paul Roub