Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const prefix on output pointers

I have this piece of C++ code that I felt a little confusing:

int foo (const char* &bar)

In this case, if I want to write to the bar pointer as:

bar = ...

It is ok. So How should I understand this const. How a const pointer different from a pointer points to a const value?

like image 994
Allan Jiang Avatar asked Dec 25 '22 21:12

Allan Jiang


2 Answers

const applies to whatever is to the left of it, unless there is nothing to the left of it, in which case it applies to whatever is to the right of it. That means in your case, bar is a reference to a pointer to a const char. bar itself is not constant and can be modified.

If you change bar to be char * const &bar, that is - a reference to a constant pointer to char, you won't be able to make that assignment. Example:

int foo (char * const &bar)
{
    bar = 0;
    return 1;
}

and trying to compile it:

$ clang++ -c -o example.o example.cpp
example.cpp:3:9: error: read-only variable is not assignable
    bar = 0;
    ~~~ ^
1 error generated.
make: *** [example.o] Error 1

You can use cdecl/c++decl to parse these declarations if they're causing you trouble:

$ c++decl
Type `help' or `?' for help
c++decl> explain const char * &bar
declare bar as reference to pointer to const char
c++decl> explain char * const &bar
declare bar as reference to const pointer to char
like image 103
Carl Norum Avatar answered Jan 07 '23 15:01

Carl Norum


If a pointer is const, you aren't allowed to assign to the pointer. E.g.

char * const bar;

bar = ...; // This is invalid
*bar = ...; // This is OK
bar[i] = ...; // This is OK

If a pointer points to a const value, you aren't allowed to assign to what the pointer points to. E.g.

const char *bar;

bar = ...; // This is OK
*bar = ...; // This is invalid
bar[i] = ...; // This is invalid
like image 29
Barmar Avatar answered Jan 07 '23 15:01

Barmar