Why does this code give the output C++Sucks
? What is the concept behind it?
#include <stdio.h> double m[] = {7709179928849219.0, 771}; int main() { m[1]--?m[0]*=2,main():printf((char*)m); }
Test it here.
&n writes the address of n . The address of a variable points to the value of that variable.
Semantic ErrorA semantic error will be generated if the code makes no sense to the compiler, even though it is syntactically correct. It is like using the wrong word in the wrong place in the English language. For example, adding a string to an integer will generate a semantic error.
Examples. This example function in C to calculate the average of two numbers contains a logic error. It is missing parentheses in the calculation, so it compiles and runs but does not give the expected answer due to operator precedence (division is evaluated before addition).
The number 7709179928849219.0
has the following binary representation as a 64-bit double
:
01000011 00111011 01100011 01110101 01010011 00101011 00101011 01000011 +^^^^^^^ ^^^^---- -------- -------- -------- -------- -------- --------
+
shows the position of the sign; ^
of the exponent, and -
of the mantissa (i.e. the value without the exponent).
Since the representation uses binary exponent and mantissa, doubling the number increments the exponent by one. Your program does it precisely 771 times, so the exponent which started at 1075 (decimal representation of 10000110011
) becomes 1075 + 771 = 1846 at the end; binary representation of 1846 is 11100110110
. The resultant pattern looks like this:
01110011 01101011 01100011 01110101 01010011 00101011 00101011 01000011 -------- -------- -------- -------- -------- -------- -------- -------- 0x73 's' 0x6B 'k' 0x63 'c' 0x75 'u' 0x53 'S' 0x2B '+' 0x2B '+' 0x43 'C'
This pattern corresponds to the string that you see printed, only backwards. At the same time, the second element of the array becomes zero, providing null terminator, making the string suitable for passing to printf()
.
More readable version:
double m[2] = {7709179928849219.0, 771}; // m[0] = 7709179928849219.0; // m[1] = 771; int main() { if (m[1]-- != 0) { m[0] *= 2; main(); } else { printf((char*) m); } }
It recursively calls main()
771 times.
In the beginning, m[0] = 7709179928849219.0
, which stands for C++Suc;C
. In every call, m[0]
gets doubled, to "repair" last two letters. In the last call, m[0]
contains ASCII char representation of C++Sucks
and m[1]
contains only zeros, so it has a null terminator for C++Sucks
string. All under assumption that m[0]
is stored on 8 bytes, so each char takes 1 byte.
Without recursion and illegal main()
calling it will look like this:
double m[] = {7709179928849219.0, 0}; for (int i = 0; i < 771; i++) { m[0] *= 2; } printf((char*) m);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With