, '=', '-'} #define PrintDigit(c, d) (for (i=0; i < c ; i+...">

For a loop in #define

#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 a function PrintDigit()that works as expected. While trying to turn the function into #define, however, gcc continues to throw a syntax error in the for loop. Any idea what the problem is?

+3
source share
3 answers

You have enclosed in parenthesis the cycle forto be deleted.

Edit

#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 the operator statement( iterativein this case) to be in the parenthesis, but it does expression.

You can look at C grammar here .

+5
source

... . , , . ( ), .

, :

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

, :

#define PrintDigit(c,d) \
     do{\
         for (int i = 0; i < c; i++ ) { \
             putchar(unit[d]); \
         }\
     }while(0)
+2
    #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;
}

()

+1

Source: https://habr.com/ru/post/1739429/


All Articles