views:

504

answers:

5

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?

+3  A: 

I'd try to declare i outside of the loop!

Good luck on solving 3n+1 :-)

OysterD
+7  A: 

There is a compiler switch which enables C99 mode, which amongst other things allows declaration of a variable inside the for loop. To turn it on use the compiler switch -std=c99

Or as @OysterD says, declare the variable outside the loop.

KiwiBastard
actually -std=gnu99 is probably more desirable since that way you still get gcc extensions (gcc defaults to -std=gnu89, however this will be changing to gnu99 at some point in the next few versions)
Spudd86
+2  A: 

I've gotten this error too.

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

is not valid C, apparantly. As OysterD says, you need to do:

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

Followup question: I take it C99 is a later standard of the C language.. how does one tell the compiler to use it? What else does it add to the language?

Blorgbeard
For gcc, throw it a "-std=c99". For additional features, see Imran's answer.
Matt J
+3  A: 

@Blorgbeard:

New Features in C99

  • inline functions
  • variable declaration no longer restricted to file scope or the start of a compound statement
  • several new data types, including long long int, optional extended integer types, an explicit boolean data type, and a complex type to represent complex numbers
  • variable-length arrays
  • support for one-line comments beginning with //, as in BCPL or C++
  • new library functions, such as snprintf
  • new header files, such as stdbool.h and inttypes.h
  • type-generic math functions (tgmath.h)
  • improved support for IEEE floating point
  • designated initializers
  • compound literals
  • support for variadic macros (macros of variable arity)
  • restrict qualification to allow more aggressive code optimization

http://en.wikipedia.org/wiki/C99

A Tour of C99

Imran
A: 

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.

boytheo
no c99 is "nicer C", if you're going to write C really do (C99 contains pretty much all the nice non-OOP/overloading related C++ features, and more, and it has fewer "gotchas" than using C++ does)
Spudd86