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();
}
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.
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.)
#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