簡體   English   中英

在宏中使用三元運算符

[英]Using the ternary operator in a macro

我正在嘗試將2個宏模板組合成第三個模板,以基本上檢查輸入的字符是否為字母。 我試圖在前兩個宏中使用三元運算符,然后使用#if指令得出結論,但是會不斷出現一些語法錯誤。 有人可以幫助我嗎?

#define SMALLCASE(X) (X>96&&X<123)?1:2); 
#define UPPERCASE(X) (X>64&&X<91)?1:2);
#define TEST(X) (SMALLCASE(X))&&(UPPERCASE(X))

/*in main() after reading character*/
#if TEST(ch)
printf("Entered character is an alphabet");
#else
printf("Entered character isn't an alphabet");
#endif
printf("%d",SMALLCASE(ch));

您在這里遇到了幾個錯誤。

  • 您不能使用#if因為預處理器不知道您將輸入的字符。
  • 使用|| 在宏TEST而不是&&
  • SMALLCASEUPPERCASE宏中的括號錯誤(僅一個(但兩個)
  • 刪除SMALLCASEUPPERCASE宏中的分號
  • 首選使用char值(如'a' )而不是其ASCII值(例如97)

然后您可以做什么:

#define SMALLCASE(X) (((X)>='a') && ((X)<='z'))
#define UPPERCASE(X) (((X)>='A') && ((X)<='Z'))
#define TEST(X) ((SMALLCASE(X)) || (UPPERCASE(X)))

/*in main() after reading character*/
if (TEST(ch)) {
    printf("Entered character is an alphabet\n");
} else {
    printf("Entered character isn't an alphabet\n");
}

首先,您必須刪除分號。 除此之外,您的宏TEST始終為真。 像這樣修改您的代碼:

#define SMALLCASE(X) ( (X) >= 'a' && (X) <= 'z' ) 
                                              // ^ removed ;
#define UPPERCASE(X) ( (X) >= 'A' && (X) <= 'Z' )
                                              // ^ removed ; 
#define TEST(X) ( SMALLCASE(X) || UPPERCASE(X) )

這是三元運算符的解決方案:

#define SMALLCASE(X) ( ( (X) >= 'a' && (X) <= 'z' ) ? 1 : 2 )
#define UPPERCASE(X) ( ( (X) >= 'A' && (X) <= 'Z' ) ? 1 : 2 )
#define TEST(X) ( SMALLCASE(X) == 1 || UPPERCASE(X) == 1 )   

此外,您不能在預處理程序語句中使用變量; 您可以使用其他預處理器語句並定義ch

#define ch 'a'

#if TEST(ch)
    printf("Entered character is an alphabet");
#else
    printf("Entered character isn't an alphabet");
#endif

或者使用if語句:

if ( TEST(ch) )
{
    printf("Entered character is an alphabet");
}
else
{
    printf("Entered character isn't an alphabet");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM