char ch = ‘D’;
cout<<ch<<endl;
cout<<&ch<<endl;
when i run this code in coding bloks online compiler then it gives D
DD
but when i run iton code bloks ide in ubuntu then it gives D
D
why?
char ch = ‘D’;
cout<<ch<<endl;
cout<<&ch<<endl;
when i run this code in coding bloks online compiler then it gives D
DD
but when i run iton code bloks ide in ubuntu then it gives D
D
why?
@MithaDev
When we write a cout statement with a character pointer , it prints till it gets a NULL character ‘\0’ .
First we print
cout << ch << endl; //Prints the first D.
Then we pass the pointer to char ch.
cout << &ch << endl;
At the memory location pointer by &ch , D is stored , so another D gets printed.
The first two D’s are fixed , they will be printed in any circumstance. After that , nothing is certain.
As I said , it will print till it encounters a ‘\0’ character. Since we have not assigned anything to the characters after ‘D’ , it will print some garbage value till it reaches ‘\0’. This garbage value in your first case came out to be just a single character ‘D’. In second case , there was no garbage value. If you run it on some other IDE or on some other system , you might get some other garbage value with some different output.
Only the first two D’s are fixed for output. Nothing can be said after that and hence the same code will give varying outputs over different runs.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.