Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I take the address of a string literal, but not of an integer literal?

Tags:

c++

I just stumbled over the following line of code

cout << &"Blahh" << endl;

The compiler doesn't give an error and on the console the address is displayed. It works all correctly without any problem. If I replace "Blahh" with an int, so

cout << &10 << endl;

the code won't compile. For short: a string literal works but an integer literal not.

What is the reason why cout << &"Blahh" << endl; works and cout << &10 << endl; not?

like image 834
System.Data Avatar asked Jan 30 '26 22:01

System.Data


1 Answers

A string literal such as "Blahh" is of type const char[6] and as such has memory allocated to it in the address space. The integer literal constant 10 does NOT have a specific memory location assigned to it and as such cannot have its address taken (as an aside, imagine if you could change the value of the constant 10 in your program).

like image 109
Mark B Avatar answered Feb 02 '26 12:02

Mark B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!