Why does this code give the output C++Sucks
? What is the concept behind it?
#include
double m[] = {7709179928849219.0, 771};
i
The others have explained the question pretty thoroughly, I'd like to add a note that this is undefined behavior according to the standard.
C++11 3.6.1/3 Main function
The function main shall not be used within a program. The linkage (3.5) of main is implementation-defined. A program that defines main as deleted or that declares main to be inline, static, or constexpr is ill-formed. The name main is not otherwise reserved. [ Example: member functions, classes, and enumerations can be called main, as can entities in other namespaces. —end example ]
The following code prints C++Suc;C
, so the whole multiplication is only for the last two letters
double m[] = {7709179928849219.0, 0};
printf("%s\n", (char *)m);
The code could be re-written like this:
void f()
{
if (m[1]-- != 0)
{
m[0] *= 2;
f();
} else {
printf((char*)m);
}
}
What it's doing is producing a set of bytes in the double
array m
that happen to correspond to the characters 'C++Sucks' followed by a null-terminator. They've obfuscated the code by choosing a double value which when doubled 771 times produces, in the standard representation, that set of bytes with the null terminator provided by the second member of the array.
Note that this code wouldn't work under a different endian representation. Also, calling main()
is not strictly allowed.