簡體   English   中英

如何使此c宏正常工作?

[英]How to get this c macro working?

為什么使用開和關宏會產生問題。 我是使用c宏的新手。 宏聲明正確還是代碼有其他問題。 請幫忙 ??

#include<stdio.h>
#include<stdint.h>

#define ONE 1;             //  OR BY   1 [ 0 0 0 0 0 0 0 1 ] TO insert 1 at LSB position             
#define TWO_FIVE_FOUR 254; // AND BY 254 [ 1 1 1 1 1 1 1 0 ] TO insert 0 at LSB position

#define on(x) (x|ONE)
#define off(x) (x & TWO_FIVE_FOUR)

int main()
{
    uint8_t a=53;

    printf("\nValue of byte a : %d",a );

    printf("\nValue of byte b : %d",on(a)); //Error

    printf("\nValue of byte c : %d",off(a)); //Error

    getchar();

    return 0;
}

從宏定義中刪除分號

#define ONE 1              //  OR BY   1 [ 0 0 0 0 0 0 0 1 ] TO insert 1 at LSB position             
#define TWO_FIVE_FOUR 254  // AND BY 254 [ 1 1 1 1 1 1 1 0 ] TO insert 0 at LSB position

您始終可以使用-E開關檢查gcc在預處理宏后如何看待您的代碼:

gcc -E mycode.c

這是輸出:

printf("\nValue of byte a : %d",a );

printf("\nValue of byte b : %d",(a|1;););

printf("\nValue of byte c : %d",(a & 254;););

很明顯的是; s是錯誤的。

啊,:)

#define是預處理程序指令,不是C語句

如果包括; 最后,預處理器會將其粘貼在代碼的中間。

您編寫的代碼可以這樣翻譯:

int main()
{
    uint8_t a=53;

    printf("\nValue of byte a : %d",a );

    printf("\nValue of byte b : %d",(a|1;););

    printf("\nValue of byte c : %d",(a & 254;););

    getchar();

    return 0;
}

只需從宏定義中刪除分號,所有分號都應該起作用。

干杯J.

暫無
暫無

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

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