Need help understanding this for loop code in C

后端 未结 5 1253
孤城傲影
孤城傲影 2021-01-11 17:22

Consider the following code in C:

void main()
{
    int a=0;

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

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


        
5条回答
  •  借酒劲吻你
    2021-01-11 17:39

    The gcc output is correct.

    The Turbo C++ 3.0 output in the first case is correct.

    The TurboC++ 3.0 output in the second case is wrong.

    You appear to have found an edge case, leading to incorrect code generation, in the Turbo C++ 3.0 compiler.

    A for-stmt in C or C++ has the general syntax

    for ( initialization ; test ; reinitialization ) stmt

    The initializations are performed once, before the loop starts. The test is performed at the TOP of the loop. If the test is true, the stmt is performed, and then the reinitializations, and the loop repeats.

    In your case, printf("\nA") is the initialization, a (or 0) is the test, printf("\nB") is the reinitialization, and the stmt is empty.

    You should have seen the A (and you did). The test should have failed on the first pass, meaning you should never have seen the stmt (but you don't know), and you should never have seen the B. This is where Turbo C++ 3.0 screwed up on the second test.

提交回复
热议问题