For loop in #define

10,121

Solution 1

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.

Solution 2

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)

Solution 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;
}

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

Share:
10,121
hspim
Author by

hspim

Updated on June 04, 2022

Comments

  • hspim
    hspim almost 2 years
    #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?

  • hspim
    hspim about 14 years
    damn, the parenthesis were the problem? struggling to see why thats an issue. thanks tho!
  • Jackson
    Jackson about 14 years
    Do you need the whole do{}while(0) piece won't a pair oof braces {} do just as well?
  • Michael Aaron Safyan
    Michael Aaron Safyan about 14 years
    @Jackson, no because of the semicolon.