I’m learning how to program in C, but I can’t figure out how to loop using a constant. Its my understanding that the best way to use a constant value in C is through the #define statement (correct me if I’m wrong). But it doesn’t seem to be working.
Here’s my code.
#include <stdio.h>
#define NUM = 3
void main(int argc, char *argv[]){
int i=0;
while(i<NUM){
printf("foo ");
i++;
}
return;
}
When I try to compile the code I get the following error.
helloWorld.c: In function ‘main’:
helloWorld.c:9: error: expected expression before ‘=’ token
(For those of you who don’t want to count, line 9 is the while loop declaration).
How can I do this using preprocessor functions, and is that the best way to use constant values in C? I can get it to work using ‘const’ but I don’t think thats best.
You use
#defineto declare a macro, which you can kind of think of as a type of constant in some cases.Actually, what happens is the compiler replaces any occurrences of your macro with your macro text. In your case,
= 3. This results inwhile(i < = 3), which is a syntax error.The correct way to write the macro is:
To define a real constant, use the
constkeyword.