Page 1 of 1

int const *i Vs const int *i

Posted: Fri Aug 13, 2004 1:20 am
by Guest
Hello all,
Could you please tell me the difference between declaring i as "int const *i" and "const int *i"?

Any help greately appreciated.

Re:int const *i Vs const int *i

Posted: Fri Aug 13, 2004 1:31 am
by Candy
Guest wrote: Hello all,
Could you please tell me the difference between declaring i as "int const *i" and "const int *i"?

Any help greately appreciated.
One of them (my guess is const int *i) is a constant pointer to a variable i. You can modify what's there, but you can't make it point somewhere else (say, a hardware register). The other is a variable pointer (which can be set to some other place), but you can't modify what's there (say, as an index into a read-only array).

Re:int const *i Vs const int *i

Posted: Fri Aug 13, 2004 2:13 am
by Guest
Then, what about this set of code? The variable i gets pointed to the variable 'b'

Code: Select all

#include<stdio.h>
main()
{
        int a=1,b=2;
        const int *i=&a;
        i=&b;
        printf("%d\n",*i);
}

Re:int const *i Vs const int *i

Posted: Fri Aug 13, 2004 2:24 am
by Legend
Then it seems that you have the pointer to constant int case ...

Re:int const *i Vs const int *i

Posted: Fri Aug 13, 2004 3:13 am
by Candy
as I'm guessing, it might also be that it doesn't matter whatsoever, both might be constant pointers to variable ints. It seems to me that there must be some way to make a variable pointer to constant ints...

after testing:

const int *a, variable pointer to constant int
int const *b, exactly the same
int *c const, gives error on compile, is nothing :)
int * const d, constant pointer to variable int

Thought the third was more likely than the last, but it is the last.

Re:int const *i Vs const int *i

Posted: Sun Aug 15, 2004 11:13 pm
by Guest
Candy wrote: int * const d, constant pointer to variable int
int main()
{
int a=4, b=5;
int * const i=&a;
printf("A = %d",*i);
i=&b;
printf("\nB = %d",*i);
}

Though the compiler produces some warning while changing the address of 'i', the output shows that the value of 'i' can be changed?

Re:int const *i Vs const int *i

Posted: Mon Aug 16, 2004 12:25 am
by Candy
Guest wrote: Though the compiler produces some warning while changing the address of 'i', the output shows that the value of 'i' can be changed?
The entire point of const is to generate compiler warnings when you override it. I believe in C you can cast it to normal char * if you want to.

Re:int const *i Vs const int *i

Posted: Mon Aug 16, 2004 1:56 am
by Neo
IIRC The effect of the 'const' keyword is implementation-defined.
If you compile the above program with a C compiler it only gives you a warning but a C++ compiler gives an error.
The purpose of 'const' is to announce that objects may be placed in read-only memory and perhaps increase opportunities for optimization
HTH