I’m trying to write some microcontroller code using Texas Instruments examples, and it uses macros everywhere (probably to reduce code size), some of which are surrounded by st(). After reading the comments, I still don’t understand why this is necessary or when I should use it:
/*
* 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)
Can you give some examples of what would fail when the st is not there? Is there any harm in adding the st where it’s not necessary?
What might st stand for? When does the second example with { something } produce compiler errors? Because that’s used in some example code, too.
The “do {…} while (0)” is a technique used to avoid some types of problems.
The
__LINE__ == -1probably was used to avoid some compiler warning.__LINE__ == -1will always be false.Take a look at this link and it will explain the reason for the “do… while(0)”
http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/