Static variable in the initial for for loop declaration

I would like to know why I cannot declare a static variable in the loop initialization for, as shown below,

for(static int i = 0;;)

Compiling the above loop statement code with my standard compiler C99. I see the error below:

error: declaration of static variable ‘i’ inforloop initial declaration
+4
source share
4 answers

C does not allow it

C11dr 6.8.5 Iterative statements 3

"The operator declaration part forshould only declare identifiers for objects that have a storage class autoor register."

(not static)


, , static.


:

typedef
extern
static
_Thread_local
auto
register
+6

for .

// i does not exist here
for (int i = 0;;) {
  // i exists here
}
// i does not exist here

static , , .

{
  static int i = 0; // i will be set to 0 the first time this is called
  i++;
}

, for static, , !

// i will not be initialized to 0 the second time this loop runs and we cannot
// initialize it here, before the loop block
for (static int i = 0;;) {
  // ...
}
+5

, g++ 4.4.3.

#include <stdio.h>

#define LOG() testPrintfPtr
#define LOG_ONCE() \
    for (static bool __only_once_ = 0; !__only_once_; __only_once_ = true) \
        LOG()

struct test {
    void debug(const char *str) {
        printf("%s\n", str);
    }
};

test *testPrintfPtr = new test();

int main() {
    for (int i = 0; i < 10; ++i)
        LOG_ONCE()->debug("ciao 1");

    LOG_ONCE()->debug("ciao 2");

    return 0;
}

, api ( LOG()), .

:

$ ./testLogOnce
ciao 1
ciao 2

I assume the C ++ standard allows this?

+2
source

What are you trying to accomplish?

If you are trying to access a variable ioutside the loop for, you will have to declare it outside the loop for:

int i;
for(i = 0; ; )
{
}
printf("%d\n", i);

If you want the loop to be forexecuted only the first time the function is called, create a staticboolean variable to handle it.

static bool firstTime = true;

if(firstTime)
{
    for(int i = 0; ; )
    {
    }

    firstTime = false;
}
+1
source

All Articles