How do I declare several variables in a for (;;) loop in C?

前端 未结 7 1017
野性不改
野性不改 2020-12-03 00:50

I thought one could declare several variables in a for loop:

for (int i = 0, char* ptr = bam; i < 10; i++) { ... }

But I just

7条回答
  •  一向
    一向 (楼主)
    2020-12-03 01:23

    It's true that you can't simultaneously declare and initialize declarators of different types. But this isn't specific to for loops. You'll get an error if you do:

    int i = 0, char *ptr = bam;
    

    too. The first clause of a for loop can be (C99 §6.8.5.3) "a declaration" or a "void expression". Note that you can do:

    int i = 0, *j = NULL;
    for(int i = 0, *j = NULL;;){}
    

    because i and *j are both of type int. The exact syntax for a declaration is given in §6.7

提交回复
热议问题