Can someone explain to me whats happening in this code step by step, c++
Yes. You first need to read a good C++ programming book.
Then you could read some C++ standard, perhaps n3337 or newer. In particular about casts expressions §5.4.
Look also into this C++ reference website. About explicit casts. Some people prefer reinterpret_cast<int>(c)
to (int)c
for readability reasons.
Read also the documentation of your C compiler, e.g. GCC. You would want to invoke it as g++ -Wall -Wextra -g
.
You could also run g++ -Wall -Wextra -O -fverbose-asm your-code.cc
and look into the assembler code your-code.s
. Probably, that emitted assembler code won't change much if you replace (int)c
by reinterpret_cast<int>(c)
Once the compiler gives no warnings, use the debugger, e.g. GDB to understand the behavior of your program.
Your cast (int)c
shows a integer (for example 65
). Without it, it shows a character (for example A
- for the same value c
- in your computer the (char)65
-and in all mines, -both at work, rented as VPS, in my pocket -my phone-, and at home- is exactly the literal 'A' unless your computer is not using ASCII -or its superset UTF8-. Today that is uncommon: few computers are using EBCDIC).
The debugger would give you the same information, and the ability to run your code step by step. Since GDB has a step
command. So learning to use GDB will win you a lot of work.
Notice that in 2021 UTF-8 is used everywhere, and things are more complex if you want to accept inputs like µ or § or é or °. On my AZERTY keyboard, I can type that with a single keystroke. And €
can be typed easily too... These characters are not ASCII!
You could also use the Clang static analyzer (or, in spring 2021, Bismon), and perhaps some C++ variant of Frama-C, perhaps called Frama-Clang. The DECODER project could be useful too.
In theory, A
might not be encoded as 65. In the 1970s I programmed on punched cards, and at that time the encoding was EBCDIC. Today you need to got into computer museums to find computers which don't encode the A
character as the 65 decimal number, or 0x41 in hexadecimal.
Some computers are still using EBCDIC, but I never met such a computer in this century.