简体   繁体   中英

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

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?

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).

Because "Blahh" has an address in memory (it's an l-value). 10 doesn't (it's an r-value).

http://en.wikipedia.org/wiki/Value_%28computer_science%29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM