Hello all,
Could you please tell me the difference between declaring i as "int const *i" and "const int *i"?
Any help greately appreciated.
int const *i Vs const int *i
Re:int const *i Vs const int *i
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).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.
Re:int const *i Vs const int *i
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
Then it seems that you have the pointer to constant int case ...
Re:int const *i Vs const int *i
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.
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
int main()Candy wrote: int * const d, constant pointer to variable int
{
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
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.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?
Re:int const *i Vs const int *i
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.
If you compile the above program with a C compiler it only gives you a warning but a C++ compiler gives an error.
HTHThe purpose of 'const' is to announce that objects may be placed in read-only memory and perhaps increase opportunities for optimization
Only Human