+ 13
Clarification of challenge question from Hatsy Rei
What is the output of this code? char a = 'a'; static_cast <int>(a)+1 //what does this mean? cout <<a; Ans:a How did we get the output as 'a'?
10 ответов
+ 18
*Star wars Dark Side music plays*
*Space capsule opens, gas everywhere, Darth Rei steps out*
Welcome to the Dark Side... !!!!
--- ---
char a = 'a';
static_cast <int>(a)+1;
cout <<a;
What static_cast does here, is to cast (a) to int ASCII value and return to where it is called. The catch here is that static_cast is not printed, and static_cast doesn't 'convert' what is stored in a variable - It simply casts them. So, in order to correctly cast character a to int and output it, the code should have been:
char a = 'a';
cout << static_cast <int>(a);
Adding 1 to the static_cast statement was just a trick. Some may think that char a would end up storing 'b', but no.
+ 13
In case you wanted the output to be 'b'... There are a few ways to do it, but if you wanted to go for static_cast...
char a = 'a';
cout << static_cast<char>(static_cast<int>(a) + 1);
+ 11
It's a modification of typing, on a line, all by itself:
a;
If you want to compare, try exactly that (stating a value) in Python interactive mode vs. running a program: What should the 'program runner' (immediate mode interpreter vs. runtime/compiler) do with a statement with no left-hand side?
+ 9
Thanks for the clarification, Hatsy Rei! 🍪
+ 9
Tyvm ☺
+ 8
Go through a very good article on data type conversion at
http://www.cplusplus.com/doc/tutorial/typecasting/
+ 8
Is it covered in the C++ tutorial here?
Thanks for the answer, luka! 👍
+ 8
@Hatsy Exactly where I went wrong haha. I typed in 'b' as the answer and was very confused when it was wrong. Thanks for clearing it up
Edit: Can you give the syntax in case I wanted the output to be "b'
+ 8
One thing I hoped someone would add here (maybe Ace, if he'd seen it):
test.cpp:6:21: warning: expression result unused [-Wunused-value]
static_cast <int>(a)+1; //what does this mean?
~~~~~~~~~~~~~~~~~~~~^~
1 warning generated.
SoloLearn and many online compilers have warnings OFF or...hidden/sometimes I see them (the -W shows which of mine fired).
Some compilers, in certain modes, will even OMIT lines (if inlined), causing weird bugs (if you intend to call while discarding the result).
+ 7
looks like typical c++ sorcery to me