-3
#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);

DilumN
  • 2,889
  • 6
  • 30
  • 44
Gurmanjot Singh
  • 10,224
  • 2
  • 19
  • 43
  • 9
    The compiler sees `(while(1<5){printf("%d < %d\n",1,5); ++1;})` – Spikatrix Oct 03 '15 at 12:42
  • 3
    To be more precise, the error you *currently* get is because of the parentheses. But removing them is not enough; then you get `error: expression is not assignable` on `++1;`. So, I guess it's time to go back to the study books. – Jongware Oct 03 '15 at 12:46
  • 2
    You aren't getting anything while executing this code. You are getting a compilation error while compiling it. – user207421 Oct 03 '15 at 13:02
  • 1
    Why on earth are you using a macro? – Ed Heal Oct 03 '15 at 13:03
  • @Jongware I removed the parenthesis and made the following changes to this snippet...It is working fine now: #include #define PRINT(a,b) while(a – Gurmanjot Singh Oct 03 '15 at 13:04

3 Answers3

3

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.

Gowtham
  • 1,465
  • 1
  • 15
  • 26
1

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); \
 }
ameyCU
  • 16,489
  • 2
  • 26
  • 41
1

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.

Coffee'd Up Hacker
  • 1,356
  • 11
  • 23