Click here to Skip to main content
15,895,494 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I understand the importance of using const in function declarations but I noticed something that I could use some input on.

The following snippet compiles without error
C++
bool Foo(const char* str)
{
    if ( str = nullptr ) { return false; } //Intentional reassignment
}

However
C++
bool Foo(char* const str)
{
    if ( str = nullptr ) { return false; } //Intentional reassignment
}

Throws an assignment error.

From the eye of compiler, what is the difference between these two function calls?
I guess I am looking for a little clarification on the enigmatic const.
Posted

1 solution

C++
char* const str


Declares a const pointer. Thus the pointer is immutable and the address value it is initialised with cannot be changed. It can't be pointed to another variable. The variable it points to may be changed.

So
C++
str = nullptr
is not allowed.

But:

C++
const char* str


declares a pointer to a const. Thus the pointer may be changed but the variable it points to may not be.

So
C++
str = nullptr
is allowed.


http://www.thegeekstuff.com/2012/06/c-constant-pointers/[^]

http://www.parashift.com/c++-faq/const-correctness.html[^]
 
Share this answer
 
v3
Comments
Foothill 26-Aug-13 23:12pm    
Thanks. The fact that every word of code in C++ means so much and that there is so much you can and can't do makes it challenging. Thank you for the clarification.
[no name] 26-Aug-13 23:15pm    
Thanks - there are a great many good pointer and const tutorials on the net.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900