2012-01-18 12 views
2

私はテキサスインスツルメンツの例を使っていくつかのマイクロコントローラコードを書こうとしていますが、どこでもマクロを使用しています(おそらくコードサイズを減らすため)、その一部はst()で囲まれています。コメントを読んだ後、私はまだこれが必要な理由を理解していないか、私はそれを使用する必要がある場合:このマクロはなぜ使用されていますか?

/* 
* This macro is for use by other macros to form a fully valid C statement. 
* Without this, the if/else conditionals could show unexpected behavior. 
* 
* For example, use... 
* #define SET_REGS() st(ioreg1 = 0; ioreg2 = 0;) 
* instead of ... 
* #define SET_REGS() { ioreg1 = 0; ioreg2 = 0; } 
* or 
* #define SET_REGS() ioreg1 = 0; ioreg2 = 0; 
* The last macro would not behave as expected in the if/else construct. 
* The second to last macro will cause a compiler error in certain uses 
* of if/else construct 
* 
* It is not necessary, or recommended, to use this macro where there is 
* already a valid C statement. For example, the following is redundant... 
* #define CALL_FUNC() st( func(); ) 
* This should simply be... 
* #define CALL_FUNC() func() 
* 
* (The while condition below evaluates false without generating a 
* constant-controlling-loop type of warning on most compilers.) 
*/ 
#define st(x)  do { x } while (__LINE__ == -1) 

あなたは目がないとき失敗するであろうもののいくつかの例を与えることはできますか?それは必要ではないstを追加する上で害がありますか?

stは何を表しますか? { something }の2番目の例はいつコンパイラエラーを生成しますか?これは、いくつかのサンプルコードでも使用されているためです。

答えて

8

「do {...} while(0)」は、いくつかの種類の問題を回避するために使用される手法です。

__LINE__ == -1はおそらくコンパイラの警告を回避するために使用されました。 __LINE__ == -1は常に偽になります。

このリンクを見て、例

http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/

+0

ここでは別の説明です:http://www.bytecraft.com/do_nothing_macro – endolith

4

それは "(0)ながら...やる" の理由を説明します:

#define a(x) if(x) { printf("%s\n", "OK"); } 
int i = 1; 
if(0) 
    a(i); 
else 
    printf("%s\n", "KO"); 

が何かに拡大します以下に相当します。

if(0) 
{ 
    if(x) 
    { 
     printf("%s\n", "OK"); 
    } 
    else printf("%s\n", "KO"); 
} 

ただし、a(x)よう:

#define a(x) st(if(x) { printf("%s\n", "OK"); }) 

それはに拡大し、動作します:

if(0) 
{ 
    do 
    { 
     if(x) 
     { 
      printf("%s\n", "OK"); 
     } 
    } 
    while(0); 
} 
else printf("%s\n", "KO"); 
関連する問題