const-correctness: what ist wrong ith this code???

W

wimalopaan

#include <iostream>

char a = 'b';
void foo(const char** ccPtr) {
*ccPtr = &a;
}

int main() {
const char x = 'a';
const char* cPtr = &x;

foo(&cPtr); // &cPtr is of type const char**

std::cout << "x: " << x << std::endl;
// oops!!!
}
 
A

Alan Johnson

wimalopaan said:
#include <iostream>

char a = 'b';
void foo(const char** ccPtr) {
*ccPtr = &a;
}

int main() {
const char x = 'a';
const char* cPtr = &x;

foo(&cPtr); // &cPtr is of type const char**

std::cout << "x: " << x << std::endl;
// oops!!!
}

I don't think there are any errors in this code. Are you getting a
compile error of some sort? A runtime error?
 
A

Andrey Tarasevich

wimalopaan said:

There's absolutely nothing wrong or unusual about this code. What are
you talking about? What is your "oops" supposed to mean?
 
W

wimalopaan

I don't think there are any errors in this code.  Are you getting a
compile error of some sort?  A runtime error?

Well, no compile error, but "sort of" runtime error.

What I mean is: why can I change the const-variable x?
 
M

Marcel Müller

Hi,
Well, no compile error, but "sort of" runtime error.

What I mean is: why can I change the const-variable x?

You cannot change x. And you do not change x.
You change cPtr. But this is not used any more.


Marcel
 
W

wimalopaan

Well, no compile error, but "sort of" runtime error.

What I mean is: why can I change the const-variable x?

Oh, my fault - it was a bit too early this morning.
Please forget the discussion!
 
S

Salt_Peter

#include <iostream>

char a = 'b';
void foo(const char** ccPtr) {
*ccPtr = &a;

}

int main() {
const char x = 'a';
const char* cPtr = &x;

foo(&cPtr); // &cPtr is of type const char**

std::cout << "x: " << x << std::endl;
// oops!!!

}

foo receives a pointer to a char* by value, and you then modified that
*local* pointer.
oops, foo no longer has a local pointer to a pointer to x.

If you wanted to modify x, why not just pass x by reference?
Who needs pointers?

void foo(char& rc)
{
rc = 'b';
}

int main()
{
char x('a');
foo(x);
}

and the equivalent using dumb pointers would have been:

void foo(char* const rc)
{
*rc = 'b';
}

where that const is the key, it prevents accidentally reseating the
pointer.
References don't suffer from such illnesses because you can't reseat
them, const or not.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top