Unusual code.

Hi all,

I'm using gcc 3.4.2. The following code compiles and prints "Hi there!".


void print() {
printf("Hi there!");

int main()
int i;
printf; "Hello", i;
return 0;

Plz explain.
Thanks and regards,



  • Well, in the lines I've commented below, the code seems to have statements that will evaluate and print something first. But, when you look closer, it is garbage code that evaluates to a long hand version of "Do Nothing.". Follow the comments.
    : [code]
    : #include
    : void print() {
    : printf("Hi there!");
    : }
    : int main()
    : {
    : int i;/* First statement, actually allocates an integer. */
    : printf; "Hello", i; /* This line is actually two separate
    * statements. The printf is "called"
    * as a pointer argument function and
    * returns a pointer to the function.
    * The next statement is a comma operation
    * that is purposely vague and meaningless
    * to disquise the fact that the printf is
    * called with null arguments. The lack of
    * parantheses and presence of an extra
    * semi-colon should cue you here. The 2nd
    * statement evaluates to the origianl
    * value of 'i', but is not used. Another
    * do-nothing. */
    : getchar;/* Another function pointer that is not used or
    * assigned to a variable. */
    : print();/* Calls a real user defined function that calls
    * printf with the argument "Hi, there!" */
    : getchar();/* Calls getchar. */
    : return 0;
    : }
    : [/code]

    The following is what the help sheet has to say about the function of commas other than in an argument list:
    The left operand E1 is evaluated as a void expression, then E2 is evaluated to give the result and type of the comma expression. By recursion, the expression

    E1, E2, ..., En

    results in the left-to-right evaluation of each Ei, with the value and type of En giving the result of the whole expression.

    I hope that this helps demonstrate that in C you can have a lot of obfuscating code and still produce a program that compiles and runs. The statements here are all acceptable to the compiler and do no harm to the running program execution, but they don't contribute anything either and would slow the execution some also. Good luck.
  • Hi Griz!

    Thanks a lot for a beautiful explanation.


  • : Hi Griz!
    : Thanks a lot for a beautiful explanation.
    : Regards,
    : Arun
    For fun, take a look here:

    Eric Goldstein

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!