#include<stdio.h>
#define PRINT(a,b) (while(a<b){printf("%d < %d\n",a,b); ++a;})
int main(void)
{
PRINT(1,5);
return 0;
}
I am getting a expression syntax error for the line PRINT(1,5);
#include<stdio.h>
#define PRINT(a,b) (while(a<b){printf("%d < %d\n",a,b); ++a;})
int main(void)
{
PRINT(1,5);
return 0;
}
I am getting a expression syntax error for the line PRINT(1,5);
The C compiler is seeing the code output from C language preprocessor. You can run the preprocessor directly to figure out which part of the processed code is the compiler having trouble with. Once you understand how the preprocessor works, you will be able to spot such errors without having to do this.
In my gnu gcc environment, cpp
does the job:
% cpp <your source file name>
Will print lots of code but at the end, you will see
int main(void)
{
(while(1<5){printf("%d < %d\n",1,5); ++1;});
return 0;
}
Do you see what is wrong here? while statement is not an expression, so it cannot be enclosed in (). Next, ++1 is not allowed because 1=1+1
does not make sense. You need to use a variable.
You got explanation in comment why you get error. To get correct you can do this -
#define PRINT(a,b) \
for(int i=(a);i<(b);i++) \
{ \
printf("%d < %d\n",i,b); \
}
As "Cool Guy" said the compiler "sees" the values passed to the macro, as if you typed them out, not as variables, and definitely not as actual typed variables.
What you want is probably:
#define PRINT(a, b) int c=(a);while(c<(b)){printf("%d < %d\n", c, (b));++c;}
To make it clearer, though...
#define PRINT(a, b) \
int c = (a); \
\
while (c < (b)) { \
printf ("%d < %d\n", c, (b)); \
++c; \
}
This is assuming you actually need a while
loop, though.
Otherwise use a for
loop instead, it's easier, and cleaner.