Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple string literals to const char* in same assignment statement

Tags:

c++

string

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?

like image 553
Vencat Avatar asked Mar 22 '19 08:03

Vencat


People also ask

Can const char * be reassigned?

Variables defined with const cannot be Redeclared. Variables defined with const cannot be Reassigned. Variables defined with const have Block Scope.

Is a string literal a const char *?

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.

What is the difference between const char * and string?

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.

How do you make a multiline string in C++?

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.


1 Answers

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.

like image 142
john Avatar answered Nov 14 '22 21:11

john