2010-04-01 129 views
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; 
} 

我有這裏的功能PrintDigit()它按預期工作。當試圖將函數轉換爲#define時,gcc一直在for循環中拋出一個語法錯誤。任何想法是什麼問題?For循環在#define

回答

5

您已將for循環括起來,您需要刪除該括號。

變化

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

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

編輯:

這樣做的原因是,C語法不允許statement(在這種情況下iterative語句),以在括號內,但允許expression

你可以看看C語法here

+0

該死,括號是問題?努力想明白爲什麼這是一個問題。感謝壽! – hspim 2010-04-01 07:08:00

+0

@hspim:已更新我的答案。 – codaddict 2010-04-01 07:16:45

1
#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; 
} 

您需要刪除()中的 聲明,結束

2

這是一個可怕的想法...你應該只讓它作爲一個內嵌功能。但是,問題在於你已經將括號中的定義放在了括號內,這使得它不正確。刪除括號並在最後刪除分號(以便您可以在其後放置分號),並且它應該可以工作。通過將其在內部範圍

 
#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) 
+0

你是否需要整個do {} while(0)piece不會與一對括號{}一樣好? – Jackson 2010-04-01 07:14:52

+0

@Jackson,不是因爲分號。 – 2010-04-01 07:15:39