Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

สตริงลิเทอรัล (String Literals) ในภาษา C คืออะไร


สตริงลิเทอรัล (String Literal) คือลำดับของตัวอักษร ที่จบด้วยศูนย์ (Null terminator) เช่น:

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

สตริงลิเทอรัลใช้สำหรับกำหนดค่าเริ่มต้นให้อาร์เรย์

char a1[] = "xyz"; /* a1 เป็น char[4] เก็บ {'x','y','z','\0'} */
char a2[4] = "xyz"; /* เหมือน a1 */
char a3[3] = "xyz"; /* a3 เป็น char[3] เก็บ {'x','y','z'} ขาด '\0' */

สตริงลิเทอรัลไม่สามารถแก้ไขได้ หากพยายามเปลี่ยนค่า จะเกิดพฤติกรรมไม่ได้กำหนด (Undefined Behavior)

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

ควรกำหนดสตริงลิเทอรัลเป็น const เสมอ

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

สตริงลิเทอรัลที่เรียกว่าค่าคงที่ตัวอักษร รองรับชุดตัวอักษรต่างๆ

/* normal string literal, type char[] */
char *s1 = "abc";

/* UTF-8 string literal, type char[] */
char *s3 = u8"abc";

/* 16-bit wide string literal, type char16_t[] */
char16_t *s4 = u"abc";

/* 32-bit wide string literal, type char32_t[] */
char32_t *s5 = U"abc";