Sunday, January 24, 2016

String Constants/Literals

String constants consist of any number of consecutive characters in enclosed quotation marks ("). String constants can have any valid character as part of it, including escape sequences. Example of string literal is given below
"Hello World!"
Some string constants can span multiple lines like the one given below
"First line \nSecond line \nThird line"
// Above statement when printed will look like as given below
First line 
Second line 
Third line
If you want to declare a string constant with quotation marks or backslash as part of the string, then you have to include proper escape character (\) for that. For example if you want a double quote (") as part of your string (like - Press the "Enter" button) you can do it as given below

"Press the \"Enter\" button"
// Above statement when printed will be: Press "Enter" button
Here middle two quotations are to be included in the string constant and so are used with escape sequences. In C programming language, system internally stores the string as a character array with a null character(\0) as the terminator. ie; null character marks the end of a string. After declaring a string constant, system automatically adds a null character(\0) after it, which denotes the end of string, as given below.
  1. char my_string[] = "My String";
  2. // Compiler will interpret the above statement as
  3. char my_string[10] = {'M', 'y', ' ', 'S', 't', 'r', 'i', 'n', 'g', '\0'};

No comments: