Does C11 allow variable declarations at any place in a function?

扶醉桌前 提交于 2019-12-01 22:06:58

Yes. This was already valid in C99 (see the second bullet here).

More or less. C99 introduced the ability to declare variables part way through a block and in the first section of a for loop, and C2011 has continued that.

void c99_or_later(int n, int *x)
{
    for (int i = 0; i < n; i++)  // C99 or later
    {
         printf("x[%d] = %d\n", i, x[i]);
         int t = x[i];           // C99 or later
         x[0] = x[i];
         x[i] = t;
    }
}

You might also note that the C++ style tail comments are only valid in C99 or later, too.

If you have to deal with C compilers that are not C99 compliant (MSVC, for example), then you can't use these (convenient) notations. GCC provides you with a useful warning flag: -Wdeclaration-after-statement.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!