What are Character and String Constants- Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Elements of C · Lecture 3

Character and String Constants

Why a quoted letter is really an integer, what the hidden terminator does, and how literals live in memory. Part of our free embedded systems course.

4
Runnable programs
8
Quiz questions
6
Interview questions
Free
Forever

Text looks simple until C gets involved. Single quotes and double quotes mean completely different things, and mixing them up is a classic bug. In this lecture on character and string constants, part of our free embedded systems course, you will learn exactly what the compiler stores for 'A' and "A", how ASCII codes make arithmetic on letters possible, and why string literals are a favourite topic in product-company interviews.

The same knowledge underpins every UART driver in the free Linux device drivers course, every command parser in the free embedded Linux course, and the string handling you will meet in the free Linux kernel development course.

What You Will Learn

By the end of this lecture you can:

  • Write valid character constants and use escape sequences correctly
  • Explain that a character constant is an integer with type int in C
  • Do arithmetic on characters, such as digit-to-number and upper-to-lower conversion
  • Describe how a string constant is stored, including the invisible '\0' terminator
  • Tell 'A' from "A" and a char array from a pointer to a literal
  • Answer common interview questions on sizeof, strlen and modifying literals

Prerequisites

Lectures 1 and 2 on integer and floating constants. You should be comfortable compiling a C file with gcc. We use ASCII, the character set of virtually every Linux and embedded toolchain.

Character Constants: A Letter That Is Really a Number

A character constant is one character written inside single quotes: '9', 'D', '$', ' ' (a space), '#'. The compiler does not store a picture of the letter. It stores the integer code of that character in the machine’s character set, which on your computer is ASCII. So 'G' is the number 71 and '5' is the number 53, and you can use them in arithmetic like any other integer.

Type surprise

In C, a character constant has type int, not char. sizeof('A') is 4 on typical systems, while sizeof(char) is always 1. C++ behaves differently here, which is a popular interview comparison. Example 3 proves it on your machine.

Written asVerdictWhat the compiler says
'9', 'D', '$', '#', ' 'ValidOne character in single quotes
'four'Bad practiceGCC accepts it as a multi-character constant with warning [-Wmultichar]; the value is implementation-defined, so never use it
''Invaliderror: empty character constant
"d"Wrong typeDouble quotes make a string, not a character
yWrongWithout quotes it is an identifier, and the compiler reports it as undeclared

ASCII Codes in Character and String Constants

ASCII assigns each character a number from 0 to 127. You do not need to memorise the table, only the anchors, because letters and digits are laid out in order.

GroupRangeCodesHandy fact
Digits‘0’ to ‘9’48 to 57c - '0' converts a digit character to its value
Upper-case letters‘A’ to ‘Z’65 to 90‘G’ is 71
Lower-case letters‘a’ to ‘z’97 to 122Lower-case is upper-case + 32
Space‘ ‘32First printable character
Semicolon‘;’59Punctuation sits between the groups
Control codesnewline, tab, null10, 9, 0Written with escape sequences
What the compiler stores for the constant ‘G’
Source text‘G’
▼
Look up in execution character set (ASCII)71
▼
Value of the expression, type int71

Escape Sequences

Some characters cannot be typed inside quotes, such as a newline, or have special meaning, such as the quote itself. A backslash starts an escape sequence that stands for one character.

SequenceMeaningCode
\nNewline10
\tHorizontal tab9
\rCarriage return13
\0Null character0
\\Backslash92
\'Single quote39
\"Double quote34
\a \b \f \vAlert, backspace, form feed, vertical tab7, 8, 12, 11
\101 and \x41Octal and hex code for ‘A’65

String Constants and the Null Terminator

A string constant is zero or more characters inside double quotes: "Kumar", "593", "8", even "". C has no built-in string type. A string constant is an array of char to which the compiler appends one extra byte with value 0, written '\0'. That terminator is how functions such as printf and strlen know where the text ends, because the array itself does not remember its length.

Memory picture of the string constant “Ravi” (5 bytes)
Index 0‘R’ = 82
Index 1‘a’ = 97
Index 2‘v’ = 118
Index 3‘i’ = 105
Index 4‘\0’ = 0 (added by the compiler)

Four visible characters, five bytes. The length of the text is 4, the size of the array is 5.

Property‘A’ (character constant)“A” (string constant)
QuotesSingleDouble
What it isOne integer, 65A char array holding 65 and 0
Typeintchar[2]
sizeof on x86-6442
Can be used in c == 'A'YesNo, that would compare an address

Two more facts to keep. Adjacent literals are joined by the compiler, so "Hello " "World" becomes "Hello World", which is handy for splitting long messages across lines. And the empty string "" is not nothing: it is one byte, the terminator.

Where String Literals Live

String literals are normally placed by the linker in a read-only section called .rodata. On a microcontroller that means flash, so they cost no RAM, but any attempt to change them through a pointer is undefined behaviour and usually faults. If you need editable text, copy it into an array: char name[] = "Embedded"; creates a writable array initialised from the literal. For a pointer to a literal, declare it const char * so the compiler stops you from writing through it.

Two ways to hold the same text
char name[] = “Embedded”;A writable copy on the stack or in .data, size 9
const char *course = “Pathashala”;A pointer to read-only text in .rodata, do not modify

Hands-On: Four Programs on Character and String Constants

Example 1: Letters are numbers

Goal

Print the numeric codes of characters and use them for arithmetic.

Save this as char_codes.c:

#include <stdio.h>

int main(void)
{
    char g = 'G';
    char five = '5';

    printf("'G' = %d, '5' = %d, 'a' = %d\n", g, five, 'a');

    int digit = five - '0';
    printf("digit value = %d, plus 3 = %d\n", digit, digit + 3);
    printf("letter after G is %c\n", g + 1);
    return 0;
}

Build and run:

$ gcc -Wall -Wextra -std=c11 -o char_codes char_codes.c
$ ./char_codes
Interactive: Predict the output first, then click to check yourself.

Expected output:

'G' = 71, '5' = 53, 'a' = 97
digit value = 5, plus 3 = 8
letter after G is H
  • Passing a char to %d prints its code; passing it to %c prints the glyph.
  • five - '0' converts the character ‘5’ (53) into the number 5. This is how every number parser turns text into digits.
  • g + 1 is 72, which prints as ‘H’. The alphabet is consecutive in ASCII, so this works for letters.

Example 2: Case conversion and escapes

Goal

Convert a lower-case letter and print the numeric values of common escape sequences.

Save this as escape_demo.c:

#include <stdio.h>

int main(void)
{
    char c = 'q';

    printf("%c -> %c\n", c, c - ('a' - 'A'));
    printf("codes: \\n=%d \\t=%d \\r=%d \\0=%d\n", '\n', '\t', '\r', '\0');
    printf("a[\tb]\n");
    return 0;
}

Build and run:

$ gcc -Wall -Wextra -std=c11 -o escape_demo escape_demo.c
$ ./escape_demo
Interactive: Predict the output first, then click to check yourself.

Expected output:

q -> Q
codes: \n=10 \t=9 \r=13 \0=0
a[	b]

Upper and lower case differ by exactly 32, and 'a' - 'A' expresses that without a magic number. This works for ASCII letters only, so check that the character is a letter first in real code. The second line shows that '\n' is 10 and '\0' is 0, and the final line prints a real tab between the brackets. Escape sequences are single characters, not two.

Example 3: Sizes tell the truth

Goal

Use sizeof to expose the type of a character constant and the hidden terminator of a string constant.

Save this as char_vs_string.c:

#include <stdio.h>

int main(void)
{
    printf("sizeof('A')     = %zu\n", sizeof('A'));
    printf("sizeof(char)    = %zu\n", sizeof(char));
    printf("sizeof(\"A\")     = %zu\n", sizeof("A"));
    printf("sizeof(\"Ravi\")  = %zu\n", sizeof("Ravi"));
    printf("'A'=%d  \"A\"[0]=%d  \"A\"[1]=%d\n", 'A', "A"[0], "A"[1]);
    return 0;
}

Build and run:

$ gcc -Wall -Wextra -std=c11 -o char_vs_string char_vs_string.c
$ ./char_vs_string
Interactive: Predict the output first, then click to check yourself.

Expected output:

sizeof('A')     = 4
sizeof(char)    = 1
sizeof("A")     = 2
sizeof("Ravi")  = 5
'A'=65  "A"[0]=65  "A"[1]=0

The first line surprises almost everyone: sizeof('A') is 4 because the constant is an int. sizeof("A") is 2 and sizeof("Ravi") is 5 because of the terminator. The last line indexes into the literal: element 0 is 65 and element 1 is 0, proving that the string really contains a zero byte. This is the exact difference between 'A' and "A".

Example 4: Arrays, pointers and strlen

Goal

Compare the length of text with the size of the array, and edit a writable copy.

Save this as string_store.c:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char name[] = "Embedded";
    const char *course = "Pathashala";

    printf("strlen=%zu sizeof=%zu\n", strlen(name), sizeof(name));
    name[0] = 'e';
    printf("edited array : %s\n", name);
    printf("%s has %zu letters\n", course, strlen(course));
    return 0;
}

Build and run:

$ gcc -Wall -Wextra -std=c11 -o string_store string_store.c
$ ./string_store
Interactive: Predict the output first, then click to check yourself.

Expected output:

strlen=8 sizeof=9
edited array : embedded
Pathashala has 10 letters
  • strlen counts characters up to, but not including, the terminator: 8. sizeof of the array includes it: 9.
  • Changing name[0] works because name is our own copy.
  • course points at read-only text. We only read it; writing to it would crash or fail on most systems.
  • Never use sizeof on a pointer parameter to find a string length; it gives the pointer size.

Common Mistakes and Troubleshooting

MistakeWhat happensFix
if (c == "A")Compares a char with an address, always wrongUse c == 'A'
char c = "A";Compiler warns about converting pointer to integerchar c = 'A';
Forgetting the terminator in a hand-built arrayprintf reads past the endReserve one extra byte and store '\0'
char *p = "hi"; p[0] = 'H';Undefined behaviour, often a crashUse char p[] = "hi";
Using 'four'Implementation-defined value and a warningUse a string for more than one character
Assuming plain char is signedOn some ARM targets it is unsigned, so comparisons behave differentlyUse signed char or unsigned char when it matters

Best Practices, Performance and Security

  • Compare characters, not strings, with ==. Use strcmp for strings and == for single characters.
  • Use const char * for pointers to literals so mistakes are caught at compile time.
  • Avoid magic numbers like 48 or 32. Write '0' and 'a' - 'A'; they are readable and identical in the object code.
  • Performance: literals are stored once, in read-only memory, and identical literals are often merged by the linker. Prefer passing a pointer to a literal over copying it into RAM on small devices.
  • Security: missing terminators and unchecked copies cause buffer overflows. Always size buffers as length + 1 and prefer bounded functions such as snprintf. Never pass user input as a format string.

Quiz: Character and String Constants

Try each question on paper first. Click a question to reveal the answer.

Q1. What integer value does 'G' have in ASCII, and what about '5'?

Answer: 71 and 53.

Q2. What is sizeof('A') in C, and why?

Answer: Typically 4. A character constant has type int in C.

Q3. What is sizeof("Ravi")?

Answer: 5: four letters plus the terminating zero byte.

Q4. What does '7' - '0' evaluate to?

Answer: 7, the integer value of the digit.

Q5. What is the difference between 'A' and "A"?

Answer: 'A' is the integer 65. "A" is a two-byte array holding 65 and 0.

Q6. Which is a compile error: '', 'ab', ""?

Answer: '' (empty character constant). 'ab' compiles with a warning, and "" is a valid one-byte string.

Q7. What is the numeric value of '\n' and '\0'?

Answer: 10 and 0.

Q8. What does strlen("Embedded") return, and what does sizeof of an array initialised with that text return?

Answer: 8 and 9.

Interview Questions: Character and String Constants

These come up in embedded and product-company interviews. Answer out loud, then click.

Q1. Why is sizeof('A') 4 in C but 1 in C++?

Answer: In C a character constant is an int. C++ changed the rule so that a character literal has type char, which affects overload resolution.

Q2. What happens if you modify a string literal?

Answer: It is undefined behaviour. Literals normally sit in read-only memory, so the program typically faults. Use a char array to get a writable copy.

Q3. What is the difference between char s[] = "hi"; and char *s = "hi";?

Answer: The first is an array of 3 bytes you own and can modify. The second is a pointer to read-only literal data, and sizeof gives the pointer size.

Q4. Is plain char signed or unsigned?

Answer: It is implementation-defined. It is signed on x86 Linux and often unsigned on ARM Linux, so use explicit signedness for byte data.

Q5. How would you convert a decimal digit character to its value, and why does it work?

Answer: c - '0'. The digits are consecutive in ASCII, so subtracting the code of ‘0’ leaves the digit’s value.

Q6. What are string literals stored in on a microcontroller, and why does it matter?

Answer: Typically .rodata, which lives in flash. That saves RAM, but on Harvard-architecture chips such as AVR you need special access macros to read them.

Summary and Key Takeaways

  • Character and string constants start simple: a character constant is one character in single quotes and is really an integer of type int.
  • ASCII layout makes c - '0' and 'a' - 'A' work for digits and letters.
  • Escape sequences such as \n, \t and \0 are single characters.
  • A string constant is a char array with a hidden terminating zero, so its size is its length plus one.
  • 'A' and "A" are different things; never confuse single and double quotes.
  • Do not modify string literals; copy them into an array when you need to edit.

Conclusion

Character and string constants are the foundation of all text handling in C. Once you accept that a quoted letter is an integer and a quoted word is a null-terminated array, errors with quotes, terminators and sizes become predictable. You have seen the real sizes, the real codes and the real behaviour on your own machine.

Now that you know what values look like when typed directly, the next lecture shows how to give them names with symbolic constants, so your code says BUFFER_SIZE instead of 64 everywhere.

Frequently Asked Questions

1. Why does C have no string type?

Answer: C was designed to be close to the hardware. Strings are arrays of char with a terminator, which keeps the language small and gives you full control of memory.

2. Is this free embedded systems course good for interview preparation?

Answer: Yes. Every lecture, including this one on character and string constants, has quiz and interview sections covering the questions that product companies actually ask about C fundamentals.

3. What is the null terminator and why is it needed?

Answer: It is a byte with value 0 placed after the last character. Library functions scan until they find it, since the array does not store its own length.

4. Can I use UTF-8 characters in string constants?

Answer: Yes, bytes outside ASCII are stored as written, but strlen counts bytes, not visible characters. C11 also offers u8, u and U prefixes.

5. Why can’t I use == to compare two strings?

Answer: == compares addresses, not contents. Use strcmp to compare the characters.

6. Will I use strings in the Linux device drivers course?

Answer: Constantly: device names, log messages with printk, and device tree strings are all string constants.

Next: Symbolic Constants

Give your literals meaningful names in the next lecture of this free embedded systems course, then move on to variables. Challenge yourself: write a function that counts digits in a string using only c – ‘0’.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →