How do I fix “for loop initial declaration used ou

2019-01-04 07:54发布

I'm trying to solve the 3n+1 problem and I have a for loop that looks like this:

for(int i = low; i <= high; ++i)
        {
                res = runalg(i);
                if (res > highestres)
                {
                        highestres = res;
                }

        }

Unfortunately I'm getting this error when I try to compile with GCC:

3np1.c:15: error: 'for' loop initial declaration used outside C99 mode

I don't know what C99 mode is. Any ideas?

标签: c gcc for-loop
11条回答
做个烂人
2楼-- · 2019-01-04 08:25

I've gotten this error too.

for (int i=0;i<10;i++) { ..

is not valid in the C89/C90 standard. As OysterD says, you need to do:

int i;
for (i=0;i<10;i++) { ..

Your original code is allowed in C99 and later standards of the C language.

查看更多
乱世女痞
3楼-- · 2019-01-04 08:28

To switch to C99 mode in CodeBlocks, follow the next steps:

Click Project/Build options, then in tab Compiler Settings choose subtab Other options, and place -std=c99 in the text area, and click Ok.

This will turn C99 mode on for your Compiler.

I hope this will help someone!

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-04 08:32

Just compile in C++ mode. You don't NEED to use classes to use C++. I basically use C++ as a "nicer C" :)

I almost never use classes and never use method overiding.

查看更多
干净又极端
5楼-- · 2019-01-04 08:34

For Qt-creator: just add next lines to *.pro file...

QMAKE_CFLAGS_DEBUG = \
    -std=gnu99

QMAKE_CFLAGS_RELEASE = \
    -std=gnu99
查看更多
\"骚年 ilove
6楼-- · 2019-01-04 08:38

I had the same problem and it works you just have to declare the i outside of the loop:

int i;

for(i = low; i <= high; ++i)

{
        res = runalg(i);
        if (res > highestres)
        {
                highestres = res;
        }

}
查看更多
Emotional °昔
7楼-- · 2019-01-04 08:39

Jihene Stambouli answered OP question most directly... Question was; why does

for(int i = low; i <= high; ++i)
{
    res = runalg(i);
    if (res > highestres)
    {
        highestres = res;
    }
}

produce the error;

3np1.c:15: error: 'for' loop initial declaration used outside C99 mode

for which the answer is

for(int i = low...

should be

int i;
for (i=low...
查看更多
登录 后发表回答