Where can I legally declare a variable in C99?

前端 未结 3 1585
无人共我
无人共我 2020-12-18 17:50

When I was first introduced to C I was told to always declare my variables at the top of the function. Now that I have a strong grasp of the language I am focusing my effor

3条回答
  •  执念已碎
    2020-12-18 18:05

    In C99, you can declare your variables where you need them, just like C++ allows you to do that.

    void somefunc(char *arg)
    {
        char *ptr = "xyz";
        if (strcmp(arg, ptr) == 0)
        {
            int abc = 0;    /* Always could declare variables at a block start */
    
            somefunc(arg, &ptr, &abc);
    
            int def = another_func(abc, arg);   /* New in C99 */
            ...other code using def, presumably...
        }
    }
    
    • You can declare a variable in the control part of a 'for' loop:

        for (int x = 0; x < 10; x++)    /* New in C99 */
      
    • You cannot declare a variable in the control part of a 'while' loop or an 'if' statement.

    • You cannot declare a variable in a function call.

    • Obviously, you can (and always could) declare variables in the block after any loop or an 'if' statement.

    The C99 standard says:

    6.8.5.3 The for statement

    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. If clause-1 is a declaration, the scope of any variables it declares is the remainder of the declaration and the entire loop, including the other two expressions; it is reached in the order of execution before the first evaluation of the controlling expression. If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.

提交回复
热议问题