tags:

views:

70

answers:

3
#include <stdio.h>
#define UNITS {'*', '#', '%', '!', '+', '$', '=', '-'}

#define PrintDigit(c, d) (for (i=0; i < c ; i++)putchar(unit[d]);)

char unit[] = UNITS;

//void PrintDigit(c, element) {
//  int i;
//  for (i=0; i < c ; i++)
//      putchar(unit[element]);
//}


int main( ) {
    int i, element=4;
    PrintDigit(10, element);
    putchar('\n');
    return 0;
}

I have the function here PrintDigit() which works as expected. When attempting to turn the function into a #define however gcc keeps throwing a syntax error on the for loop. Any idea what the problem is?

+2  A: 

You've enclosed the for loop in parenthesis, which you need to remove.

Change

#define PrintDigit(c, d) (for(i=0; i < c ; i++)putchar(unit[d]);)

to

#define PrintDigit(c, d) for(i=0; i < c ; i++)putchar(unit[d]);

EDIT:

The reason for this is that the C grammar does not allow a statement (iterative statement in this case) to be inside parenthesis but allows an expression.

You can take a look at the C grammar here.

codaddict
damn, the parenthesis were the problem? struggling to see why thats an issue. thanks tho!
hspim
@hspim: Have updated my answer.
codaddict
A: 
    #include <stdio.h>
    #define UNITS {'*', '#', '%', '!', '+', '$', '=', '-'}

    #define PrintDigit(c, d) for (i=0; i < c ; i++)putchar(unit[d]);

    char unit[] = UNITS;

    //void PrintDigit(c, element) {
    //  int i;
    //  for (i=0; i < c ; i++)
    //      putchar(unit[element]);
    //}


    int main( ) {
    int i, element=4;
    PrintDigit(10, element);
    putchar('\n');
    return 0;
}

You need to remove the () in the for statement before and end

muruga
A: 

This is a terrible idea... you should just make it an inline function. However, the problem is that you have surrounded your definition in parentheses which makes it incorrect. Remove the parentheses and also remove the semicolon at the end (so that you can place a semicolon after it), and it should work.

In other words, change your definition to:

#define PrintDigit(c, d) \
    for (int i = 0; i < c ; i++) \
        putchar(unit[d])

You can make this a little bit less fragile by putting it in an inner scope:

#define PrintDigit(c,d) \
     do{\
         for (int i = 0; i < c; i++ ) { \
             putchar(unit[d]); \
         }\
     }while(0)
Michael Aaron Safyan
Do you need the whole do{}while(0) piece won't a pair oof braces {} do just as well?
Jackson
@Jackson, no because of the semicolon.
Michael Aaron Safyan