Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help understanding this for loop code in C

Tags:

c

Consider the following code in C:

void main()
{
    int a=0;

    for(printf("\nA"); a; printf("\nB"));

    printf("\nC");
    printf("\nD");     
}

When I compile it using Turb C++ version 3.0 and gcc-4.3.4, I get the following as the output in BOTH the cases :

A
C
D

However, if I compile the following code:

void main()
{
    for(printf("\nA"); 0; printf("\nB"));

    printf("\nC");
    printf("\nD");
}

The output by gcc-4.3.4 is the same as in the previous case but turbo c++ 3.0 produces the following output :

A
B
C
D

First of all, I have no idea what's happening here! Plus, how come the output by the gcc compiler is the same for both the codes but in the case of turboc++ 3.0 compiler, the output is different? Can someone please shed some light?

EDIT :

Actually someone was asked this question in an interview for an IT company and when he failed to give the answer, the interviewer gave this explanation. But I find this to be stupid. How can you ask someone to use a "bug" as if it's a "facility" provided by the language? For it to be called a "facility" and "technique", whether we pass 0 as a literal in the second expression or a variable whose value is 0, the outcome should have been the same.

Am I wrong concluding that the interviewer was very dumb to ask a question like that and that it shows his incompetence?

like image 597
finitenessofinfinity Avatar asked Jun 18 '12 16:06

finitenessofinfinity


1 Answers

The TCC output for the 2nd example is wrong.

From the C99 standard:

The statement

for ( clause-1 ; expression-2 ; expression-3 ) statement

behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression-3 is evaluated as a void expression after each execution of the loop body. [...]

Obviously, there are no iterations here, so expression-3 should never be executed.

Similarly, in the C90 standard (or at least in a draft that I found), it says:

Except for the behavior of a continue statement in the loop body, the statement

     for (  expression-1 ;  expression-2 ;  expression-3 )  statement

and the sequence of statements

      expression-1 ;
     while ( expression-2) {
               statement
              expression-3 ;
     }

are equivalent.

like image 120
Oliver Charlesworth Avatar answered Sep 21 '22 23:09

Oliver Charlesworth