Const char *p

Which one is constant?

p

or *p?

And how do we tell?

This confuses me all the way till now
When you have a pointer to some type T, the constness is as follows:
1
2
3
const T* ptr; // pointer to a constant T
T const* ptr; // pointer to a constant T
T* const ptr; // constant pointer to a T 
So,

1 and 2 is the same?

Also how do you make that nice highlight anyway?

And what rules you used?

My teacher once said

const T* ptr; for example

Well, put an invisible bracket in *ptr

So

const T (*ptr)

Now that means *ptr if of type const T. That means ptr is a pointer to a const T

That confuses me as hell.

That rule doesn't work for line 2

For line 3, let's see

T (* const ptr)

Hmm... So, * const ptr is of type T. Yap ptr is a pointer to T except that it's constant.

Why I still fill something is missing.
[code]With code tags[/code]
1
2
3
4
5
const T (*ptr);
T const (*ptr);
T (*const ptr);
const T * const ptr;
T const * const ptr;


Maybe typedef will help you
1
2
3
4
5
6
7
typedef int * ptr_int;
typedef const int * ptr_const_int;

ptr_int p; //a pointer to int
const ptr_int p; //a constant pointer to int
ptr_const_int p; //a pointer to constant int
const ptr_const_int p; //a constant pointer to constant int 
I feel that it is better to write only int const good; because it is similar to the ordering of void * const good;.
However I think const is not very useful, because a function that takes a pointer to a constant, int atoi(char const*c);, is not guaranteed to adhere to it. It might cast the const away. So the compiler cannot use const to make any optimizations.
That's why you should not cast compilations errors.
Also, without casting but with an extension http://www.cplusplus.com/forum/general/33129/
because a function that takes a pointer to a constant, int atoi(char const*c);, is not guaranteed to adhere to it. It might cast the const away. So the compiler cannot use const to make any optimizations.


The compiler can and does use const to make optimizations. In such instances where the const is cast away, you might get results you don't expect. Which is exactly why you shouldn't cast away const qualifiers.
Disch, I made a program to test that. (Is this becoming a cliche for me?)
1
2
3
4
5
6
7
8
#include "stdio.h" 
inline void modify(int const *px){	*(int*)px = 1;	}
inline int deref(int const *px){	return * px;	}
int main(){
	const int x=24;
	modify(&x);
	printf("%d %d %d %d\n",x,*&x,*(int*)&x,deref(&x));
}

Now, here is the output, for various settings:
oren-laptop% gcc const.c;./a.out    
1 1 1 1
oren-laptop% gcc -O3 const.c;./a.out
24 24 1 1
oren-laptop% g++ const.c;./a.out    
24 24 1 1

Interesting. C++ assumes more.
Last edited on
Topic archived. No new replies allowed.