[Solved] Please explain the output to this code: [closed]


This is a trick question. Presumably someone thought you could learn something from it. Presumably this person also thinks that a good way to teach a child to ride a bicycle is to flatten the bicycle’s tires, and put large boulders in the way, and randomly give the child a rough shove to the side, because it “builds character”, and if you can learn to ride a bicycle in spite of those obstacles, you will eventually be a really good bike rider. But I digress.

Anyway, here’s an explanation of what’s going on in that code.

0xA is a hexadecimal constant. It has the value 0A16, or 10 (base 10).
052 is an octal constant. It has the value 528, or 42 (base 10).
'\xeb' is a hexadecimal character constant. It is a character with the value EB16, or 235 (base 10) (which in ISO-8859-1 or Unicode ends up being an e with two dots over it, ë).
'\012' is an ordinary, octal character constant. It is a character with the value 128, or 10 (base 10) (which in ASCII ends up being a newline character, '\n').

When you say

if( expr )

in C, the expression is considered “true” if it is nonzero, or “false” if it is zero. Needless to say, all four of those constants are nonzero.

The full syntax of an if statement in C is either

if( expr )
    statement-or-block

or

if( expr )
    statement-or-block
else
    statement-or-block

where statement-or-block is either a single statement, or a “block” (sequence) of multiple statements enclodes in braces { }.

A little-used piece of syntax in C is the “empty statement”. If you have nothing, followed by a semicolon, that’s an empty statement, and it does… nothing.

It is considered mandatory in polite circles to indent your code to portray its structure. So the normal way of presenting this code would be:

#include <stdio.h>

int main()
{
    if(0xA)
        if(052)              
            if('\xeb')
                if('\012')
                    printf("Hello World!")
                else
                    ;
            else
                ;
        else
            ;
    else
        ;
}

And, again, all four expressions evaluate immediately to “true”. So, in English, this code says “If true, then if true, then if true, then if true, then print ‘Hello world!’, else do nothing, else do nothing, else do nothing, else do nothing.”

Phrased that way it sounds pretty stupid, I know. And in fact, it’s just as stupid in C as it is in English.

P.S. Besides the bizarre and unnecessary conditionals, another problem with the code as posted, which I have quietly corrected, is that it declared main as void, which is something else that’s not done in polite circles, and throws further doubt on the validity of the book this code came from.

solved Please explain the output to this code: [closed]