Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Fender2112

macrumors 65816
Original poster
Aug 11, 2002
1,141
402
Charlotte, NC
Here's the code. A simple use of a for loop.

#import <stdio.h>

int main(int argc, char *argv[])
{
int triangularNumber = 0;​
int number = 0;​

printf ("What triangular number do you want to calculate: ");​
scanf ("%i", &number);​

for (int n = 1; n <= number; n++)​
triangularNumber += n;​
printf ("Triangle number %i is %i\n", number,triangularNumber);​

return 0;​
}

The book I'm reading says that "for (int n = 1; n <= number; n++)" is a valid way of declaring and initializing a variable. There is also a footnote the says "This is a feature added to the 1999 ANSI C Standard (sometimes referred to ad C99). If you're using gcc and you get an error trying to use this feature, try adding the -std=c99 option to the command line."

I do get an error and I'm using gcc via Xcode. Is there a #import or something else that adds this feature to Xcode without having to use Terminal?
 

robbieduncan

Moderator emeritus
Jul 24, 2002
25,611
893
Harrogate
This is not Objective-C! It's just C!

You could simply move the loop variable defn so it works:

int n;
for (n=1;....
 

Fender2112

macrumors 65816
Original poster
Aug 11, 2002
1,141
402
Charlotte, NC
robbieduncan said:
This is not Objective-C! It's just C!

You could simply move the loop variable defn so it works:

int n;
for (n=1;....

This I know. I more curious to know how to access this feature with Objective C. It works fine with C++, which is where I learned it and have gotten used to using it.

I assume there is a header file that can add this feature to Objective C. If not I will have to go back to counting on my fingers and toes. :D
 

robbieduncan

Moderator emeritus
Jul 24, 2002
25,611
893
Harrogate
I seem to remember that Apples version of GCC turns this off for .m (Obj-C) files. Just learn to live without it! You could try the setting above and pass custom arguements to the compiler. I'm fairly sure you can't add language features like this in a header.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.