Possible Duplicate:
Do-While and if-else statements in C/C++ macros
gcc (GCC) 4.7.2
c89
Hello,
I have the following function-like macro and just wondering what is the preferred usage when using across multiple lines. It it better to use curly braces or do..while(0) loop.
Normally I use a do..while(0) for everything. But I have seen some projects where they just use the curly braces, and I am not sure which one would be better.
do..while
#define DSO_ERROR(msg, res_handle_module, mem_pool, size) do { \
char *dso_error = apr_palloc((apr_pool_t*)mem_pool, size); \
apr_dso_error((apr_dso_handle_t*)res_handle_module, (char*)dso_error, (apr_size_t)size); \
LOG_ERR("%s dso error %s", (char*)msg, dso_error); \
goto dso_failure; \
} while(0);
curly braces
#define DSO_ERROR(msg, res_handle_module, mem_pool, size) { \
char *dso_error = apr_palloc((apr_pool_t*)mem_pool, size); \
apr_dso_error((apr_dso_handle_t*)res_handle_module, (char*)dso_error, (apr_size_t)size); \
LOG_ERR("%s dso error %s", (char*)msg, dso_error); \
goto dso_failure; \
}
The only difference is that a semi-colon will be preset on the do..while loop and not on the curly braces.
Many thanks for any suggestions,
In programming, curly braces (the { and } characters) are used in a variety of ways. In C/C++, they are used to signify the start and end of a series of statements. In the following expression, everything between the { and } are executed if the variable mouseDOWNinText is true. See event loop.
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
The curly braces are part of Django Template Language. The part encapsulated between double curly braces {{ }} is nothing but a variable. That's how DTL, Jinja2 and other template languages work. They have their own set of rules which translates the template in to python and later to HTML code.
If the number of statements following the for/if is single you don't have to use curly braces. But if the number of statements is more than one, then you need to use curly braces.
The curly brace version will break usage like this:
if( foo )
DSO_ERROR("Foo occured!", my_module, the_pool, 4711);
else
printf("All is well, there is no foo\n");
which is the very reason for the do ... while(0)
construct. So that seems worth avoiding.
you will have a problem with this code:
if (one)
DSO_ERROR("one", ...);
else
DSO_ERROR("two", ...);
so if you use the do-while-Macro WITHOUT the semicolon, you would be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With