-2

Should be 7 in ASCII the output?

#include <bits/stdc++.h>
using namespace std; 
int main() {
    char a = '7'; 
    int b = 7;
    cout << (char)b;
}
Fabbiucciello
  • 1,514
  • 2
  • 4
  • 9

1 Answers1

2

Clearly not, because the ASCII code for '7' is 0x37 (55). ASCII 7 is the BEL control character. If supported by the particular environment you run it on, it will issue some alert sound or beep.

In this case the cast causes std::ostream::operator<<(char) rather then std::ostream::operator<<(int) to be called, emitting the character BEL ('\a' or 7) to be emitted rather then presenting a decimal string representing the integer value 7.

Clifford
  • 88,407
  • 13
  • 85
  • 165
  • std::ostream::operator<<(int) what does it mean ? – Fabbiucciello Feb 07 '21 at 12:25
  • @Fabbiucciello This is the overloaded stream operator for formatted output of `int`: [std::ostream& std::ostream::operator<<(int)](https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt). It makes that `std::cout << 123;` does what it does. – Scheff's Cat Feb 07 '21 at 12:27
  • @Fabbiucciello Maybe you should post that as a separate questuion. `<<` is an overloaded operator of the `ostream` class; it is not _built-in_ to the language. When you use `<<` and the left-hand operand is an `std::ostream` object (as `cout` is), then an `ostream` member function called `operator<<` is called of which there are several versions, and the one called depends on the _type_ of the right-hand operand. http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/ – Clifford Feb 07 '21 at 12:33