What are string literals in C language?

CServer Side ProgrammingProgramming

A string literal is a sequence of chars, terminated by zero. For example,

Char * str = "hi, hello"; /* string literal */

String literals are used to initialize arrays.

char a1[] = "xyz"; /* a1 is char[4] holding {'x','y','z','\0'} */
char a2[4] = "xyz"; /* same as a1 */
char a3[3] = "xyz"; /* a1 is char[3] holding {'x,'y','z'}, missing the '\0' */

String literals are not modifiable if you try to alter their values, which leads to undefined behavior.

char* s = "welcome";
s[0] = 'W'; /* undefined behaviour */

Always try to denote string literals as such, by using const.

char const* s1 = "welcome";
s1[0] = 'W'; /* compiler error! */

String literals also called as character constants, support different character sets.

/* normal string literal, of type char[] */
   char* s1 = "abc";
/* UTF-8 string literal, of type char[] */
   char* s3 = u8"abc";
/* 16-bit wide string literal, of type char16x[] */
   char16x* s4 = u"abc";
/* 32-bit wide string literal, of type char32x[] */
   char32x* s5 = U"abc";
raja
Published on 08-Mar-2021 07:21:38
Advertisements