String Literals
When we write a string literal
, an array
of characters
is initialized with \0
appended at the end.
void foo (const char* character) {
char c;
int index = 0;
while (
(
c = ( // (1)!
* ( // (2)!
character // (3)!
+ sizeof(char) // (4)!
* index // (5)!
)
)
)
!= '\0' // (6)!
) {
std::cout << c;
index++;
}
std::cout << std::endl;
}
int main () {
foo("hi"); // (7)!
return 0;
}
- Assignment expression evaluates to
rvalue
. Dereferencing
thepointer
to access thecharacter
stored at the memory location.- The
const char*
pointer
acting as a reference point. - The size of the offset in
bytes
(forpointer arithmetic
). - An indexed multiplier to iteratively increase the total offset (the
character
to read) relative to the reference point(thepointer
). - Condition to exit the loop, that the
character
indicates end of astring
. "hi"
results into anarray
ofcharacters
(h, i,\0
) initialized in memory.
Also, having 2 string literals
side by side does concatenation.
const char* text1 = "hello " "world";
const char* text2 = "hello world";
Both are same.