I'm new to c++ and I came across below code snippet which looks strange for me.
const char* keys = "hello" "world";
std::cout << keys << std::endl;
Above code prints helloworld in the console. Is it syntactically valid to assign two string literals to a const char* in the same statement? if so, how it will be stored in memory?
Variables defined with const cannot be Redeclared. Variables defined with const cannot be Reassigned. Variables defined with const have Block Scope.
In C++, string literals are stored in arrays of const char , so that any attempt to modify the literal's contents will trigger a diagnostic at compile time. As Christian points out, the const keyword was not originally a part of C.
string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.
The string str can be written in multiple lines by using two double quotes ( “ “ ) to break the string at any point in the middle. Then the string is displayed using puts. The code snippet that shows this is as follows.
It's a rule of C++ (and C) adjacent string literals are concatenated prior to compilation (but after macro expansion IIRC).
This happens anywhere, not just as part of an assignment statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With