简体   繁体   中英

what is difference in type between array of char and string literal

I am reading c++ programming language book and i am learning about pointer to char,
i found this code char s[] = "Gorm";
which reminds me that string literal is converted implicitly to const char *.

so i felt confused that lhs and rhs are not of same type.

i used online compiler and code from here: Is it possible to print a variable's type in standard C++?
to get idea about how compiler see type of lhs and rhs,
then i found that lhs is seen as char[5] while rhs is seen as char[5] const &
i can interpret lhs,
but i can not understand what is "constant lvalue reference to array of 5 char" or
even after implicit conversion of lhs char s[] to char* s ,
what is "constant lvalue reference to non const pointer to non const char"??

is not lvalue reference by definition constant "it refers only to value initializing it"???
so why do we need const before "&"???

and then how can lhs and rhs of different types be assigned??????

the suggested answer is really helpful in understanding how char s[] is initialized from string literal "it is language rule".

but it does not answer the part of question regarding the expression"char [5] const &"???

what is the meaning of const & in this strange expression?!!!
what is const referring to???

is it referring to the lvalue reference itself???"reference is const by definition and we can not change value of reference after initialization"???

or is it referring to the element of the array const char so that string literal array can not change????
but in this case const should have been put before char or after char not before & ?????!!!

or const is referring to the type char[5] and in this case what is its importance????
normally array can not be changed regarding size or type after definition????

Although the your question is not clear I believe the primary issue is the idea that a string literal being a different type then a char array char[] . A string literal is not a string or a char array which are data type in c++, but is a syntax structure that is defined during the compile. Another example would be a integer literal 0b00000101 this represents an integer equal to 5 but is not an integer, just like "gorm" is not a string but represents a string (more accurately a char array) to the compiler. When declaring a char array and initializing it with a string literal like you do here: char s[] = "Gorm"; . This tells the compiler to treat the string literal as a char array when initializing the char array s.

I believe looking into the concept of a literal and how it helps with initializing values in a programming langauge would be helpful. Link to Wikipedia page on Literals

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