Can anyone please explain what is going in this C++ code. It compiles and executes fine on Linux.
#include <iostream>
using namespace std;
int main = ( cout << "Hello world!\n", 195 );
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The number “195” is the code of RET instruction on x86.
The C++ compiler (gcc in my case) is unable to recognize that “main” wasn’t declared as a function. The compiler only sees that there is the “main” symbol, and presumes that it refers to a function.
The C++ code
is initializing a variable at file-scope. This initialization code is executed before the C/C++ environment calls main(), but after it initializes the “cout” variable. The initialization prints “Hello, world!\n”, and sets the value of variable “main” to 195. After all initialization is done, the C/C++ environment makes a call to “main”. The program returns immediately from this call because we put a RET instruction (code 195) at the address of “main”.
Sample GDB output: