0

i was reading a textbook that was talking about "character literal" vs "string literal." It said the following:

'A' is stored as 65

"A" is stored as 65 0

char letter;
letter = 'A' // this will work
letter = "A" // this will not work!

the textbooks explanation confused me. It said "because char variables are only large enough to hold one character, you cannot assign string literals to them." Can anyone explain further, its not clicking in my head. Thank you for your time

VickTree
  • 889
  • 11
  • 26
  • 4
    String literals (or really constant null-terminated byte strings) are actually *arrays*. The literal string `"A"` is a constant array of two character (i.e. `const char [2]`). – Some programmer dude Jan 13 '19 at 18:14

3 Answers3

3

You should see this: Single quotes vs. double quotes in C or C++

As everyone has said here, think about arrays. A character is only one leter or digit or symbol and it is declared by simple quotes. However, when you are declaring with double quotes, you are actually indicating that is about a string or array. Thus, you should declare your variable like an array. For instance:

char letter[] = "A";

Or

char *letter = "A";

If you want a static Array, You could try something like this:

char letter[5] = {'H','E','L','L','O'};

If you want see another point view, you could read this: http://www.cplusplus.com/doc/tutorial/ntcs/

Hope I was helpful.

2

What you might be missing is the fact that strings can be of arbitrary length. The compiler places the string somewhere in the program / memory the way you type it, but it needs to know where the string ends! This type of strings is known as zero- or null-terminated. It means simply that the string is the actual string data followed by a single byte with the value 0.

So in the example, 'A' is the character A. In memory, it may immediately be followed by some garbage / unrelated data, but it's fine, because the compiler knows to only ever use that one byte.

"A" is the string A. In memory, it must be followed by a null terminator, otherwise the program could get confused because there might be garbage data immediately after the string.

Aurel Bílý
  • 7,068
  • 1
  • 21
  • 34
2

Think about strings as array of characters, where one element of this array is simply 'character literal'.

Sebastian
  • 330
  • 4
  • 9