I was in lab recently when my professor noticed another student using a switch statement with characters. He noticed that it allowed "case '==':" and from there we went down a rabbit hole of what number does this equate to and how did it come to that.
I could find anything via google, so when I got home I did some maths and came up with the formula in the following code:
#include <iostream>
int main() {
int a = 'b';
int b = 'bb';
std::cout << a << std::endl << std::endl;
std::cout << b << std::endl << std::endl;
std::cout << (a * 256) + a << std::endl << std::endl;
int c = 'bbb';
std::cout << c << std::endl << std::endl;
std::cout << (a * 256 + a) * 256 + a << std::endl << std::endl;
int d = 'abcd';
std::cout << d << std::endl << std::endl;
int e = ((97 * 256 + 98) * 256 + 99) * 256 + 100;
std::cout << e << std::endl << std::endl;
return 0;
}
This provides the following output:
98
25186
25186
6447714
6447714
1633837924
1633837924
So, I figured out the math behind it, I was just wondering if anyone knew the why they chose to resolve it like this or could provide a real world example where this might be useful? It seems pretty math heavy for multi character switch statements.