Integer + string = ... new string?

Hi,

I just saw this piece of code:

1
2
3
char alphabet[26];
    for ( int i = 0; i < 26; ++i )
        alphabet[i] = i + 'a';


I don't really understand it. i + 'a', so you make a sum (the integer + the letter 'a')? Why does this work and why do you get the alphabet letters as the result?

Tyvm =)
Characters are stored as integers in computers, every character has it's own numerical value.
For example 97 == 'a'
See http://www.asciitable.com/ for more.
As in the ASCII table the English alphabet's characters are in a continuous range, we can cheat like in your example. This is equivalent to yours :
alphabet[i] = i + 97;
Also literals in double quote are "strings", and literals in single quote are 'c' characters, the latter represents a single numerical value, while the former is a 0 terminated array of numerical values.
Last edited on
Which is why typecasting between char and int work.
Numbers are from ASCII 48 (char '0') and letters from 97. The unsigned range is from 0-255.

See how well designed everything is? It all sort of 'fits together'.
This can be used as a form of encryption, however, it is a very... weak encryption.
Yes but then you could add extra operations, such as sqrt-ing to obfuscate the result.

Anyway, I think you would use hashes for that.
This particular code uses a loop to store the lowercase alphabet into
 
char alphabet[26];


What you see happening on line 3 constant value of 'a' (based on the ASCII chart) which is 97 being added to the iterator. In C and C++, integers and characters are practically the same thing and can be used together like that...

A good ASCII chart image:
// http://www.cs.utk.edu/~pham/ascii_table.jpg

Here is what it looks like simplified:
1
2
3
4
5
alphabet[0] = 0 + 97; // The letter 'a'
alphabet[1] = 1 + 97; // The letter 'b'
alphabet[2] = 2 + 97; // The letter 'c'
alphabet[3] = 3 + 97; // The letter 'd'
// etc... 


The result... an array of 26 bits with all the lowercase letters in it :)
Last edited on
Ow, I forget this thread.

Thank you very much for the replies, I understand it now :)
ahh i c... does this code print the alphabet?

anyways, thanks for posting cool algorithm.
Topic archived. No new replies allowed.