pointer to constant

There is a pointer to a constant value. why "&" need to be used to get address of that constant ?
#include<iostream.h>
#include<conio.h>
void main()
{ const int n=99;
clrscr();
const int *ptr=&n;
cout<<”address of n : “<<ptr; // gives O/P only when “&ptr” is used
getch();
}

It gives address value NOT pointing to a constant and without using "&".

#include<iostream.h>
void main()
{ int n=99;
int *ptr=&n;
cout<<"address of n : "<<ptr; //gives correct O/P here.
getch();
}
Last edited on
You must use & to get the address of a variable. It doesn't matter whether that variable is constant or not. As we can see in your second code snippet, you do use & despite the claim that you do not.
assignment statements are same in both but while outputing address Ist one needs "&" but second one dont need it.
If you use & in the first, you would be printing out the address of ptr, not the address of n, so the output would be incorrect.

What makes you think the ouput of the first snippet is incorrect without: cout << "address of n: " << &ptr;
what line should i type to get address of n using pointer ptr only?
The first snippet is correct as written (provided you remove or ignore the inaccurate comment, change the return type of main to int and iostream.h to iostream and qualify cout with the std namespace.)

http://ideone.com/cRAIxf
As per your instructions : my code

#include<iostream>
#include<conio>
int main()
{ const int n=99;
clrscr();
const int *ptr=&n; // pointer to a constant
// const int *const Cptr=&n; // constant pointer to a constant
std::cout<<*ptr<<" "<<ptr;
// cout<<"\n"<<*Cptr<<" "<<Cptr;
return (0);
getch();
}

After compiling :
Error P2.CPP 1: Unable to open include file 'IOSTREAM'
Error P2.CPP 2: Unable to open include file 'CONIO'
Error P2.CPP 5: Function 'clrscr' should have a prototype
Error P2.CPP 8: Type qualifier 'std' must be a struct or class name
Error P2.CPP 8: Statement missing;
Error P2.CPP 11: Unreachable code
Error P2.CPP 11: Function 'getch' should have a prototype
Error P2.CPP 12: Function should return a value
Error P2.CPP 12: 'ptr' is assigned a value that is never used
Topic archived. No new replies allowed.