Hi
I am a beginner in c++. And started studying integer types(int,char,long,short).
Why is it that when i write char ch = 'j'. C++ stores the ascii equivalent of the character in ch? Why not store the character directly as j?
Is there any way to store j or any such character directly in ch?
Again why do we have actual integers(0,1,2,3,4,5,6,7,8,9) as characters in c++.
When i write char ch = '1'; C++ stores the ASCII equivalent of 1 in ch.
Why do we need it when we can simply write int ch = 1?
I know my questions might be too beginner-ish. Even so thanks for reading.
That is what it does, or as directly as possible for the computer. The character 'j' is a human concept, in order for a computer to store characters, it needs to encode it using the only language it understands, which means a binary number.
Remember, we have 26 different letters, and 10 different digits, as well as lots of other symbols we can use. By contrast, the computer has just two values, the binary digits 0 and 1, with which it must encode everything which it deals with, whether text or numbers or graphics or sounds, all are made up of a lot of zeros and ones..
The integer 1 and the character '1' are not the same thing. 1 is a number. '1' is a character, the computer stores and manipulates it as a numeric value, commonly in the ASCII code, though there are other encodings.
When i write char ch = '1'; C++ stores the ASCII equivalent of 1 in ch. Why do we need it when we can simply write int ch = 1?
Because there is a difference between ASCII and binary values.
Writing ch = 1 stores the binaryvalue 1 (an ASCII SOH) into ch.
writing ch = '1' stores the ASCII value for 1 (decimal 49) into ch.
Single quotes ' are used for character literals. 'r' is a single character.
Double quotes " are used for string literals. "r" is a string of characters with a length of 1.
An ordinary character string like this can be of any length, the end of the string is marked by a terminating null character, like this:
1 2 3 4
char c = 'r'; // single character
char s[2] = { 'r', 0 }; // a string of length 1
cout << c << endl;
cout << s << endl;
What difference does it make?
The character string requires more storage space, and may be slower (though in practical terms it might be unmeasurable), since outputting the string requires a loop which tests each character until it detects the terminating null (zero byte) which marks the end of the string.