473,791 Members | 3,015 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++ faq 38.5 - macros with multiple statements

This item in the C++ faq:
http://www.parashift.com/c++-faq-lit....html#faq-38.5

discusses macros with multiple statements.

The problem is that a macro such as

#define MYMACRO(a,b) stmt1; stmt2;

will cause unwanted astonishment if you say:

while(whatever)
MYMACRO(foo,bar );
This is also problematic:

#define MYMACRO(a,b) {stmt1; stmt2;}

because this won't compile:
if(foo())
MYMACRO(i,j);
else
baz();

since you can't have "}; else"
so the faq proposes this solution:

-------------
#define MYMACRO(a, b) \
if (true) { \
statement1; \
statement2; \
... \
statementN; \
} else
-------------

But this seems like a bad solution; what if you write this:

MYMACRO(foo,bar ) // note no semicolon
baz();

it compiles fine, but baz() *never* gets called!

Is there a way to avoid this? Maybe the do/while idiom should be used
dispite the inlining problems?

// compiler may not inline functions that use this because of the loop...
#define MYMACRO(a, b) \
do { \
statement1; \
statement2; \
... \
statementN; \
} while (false)

thanks,
Erik

Jul 22 '05 #1
1 2034
"Erik Haugen" <ha****@Xenon.S tanford.EDU> wrote:
This item in the C++ faq:
http://www.parashift.com/c++-faq-lit....html#faq-38.5

discusses macros with multiple statements.
[snip]
the faq proposes this solution:

-------------
#define MYMACRO(a, b) \
if (true) { \
statement1; \
statement2; \
... \
statementN; \
} else
-------------

But this seems like a bad solution; what if you write this:

MYMACRO(foo,bar ) // note no semicolon
baz();

it compiles fine, but baz() *never* gets called!

Is there a way to avoid this? Maybe the do/while idiom should be used
dispite the inlining problems?


How about this:

#define MYMACRO(a, b) \
if (true) { \
statement1; \
statement2; \
} else true

This makes the null statement explicit, and should cause a syntax error if
no semi colon follows (if this looks weird to anyone, an expression that
does nothing like "true" or "1+3" is a valid statement in C++).

The following cases mentioned in the FAQ should work OK:

while (whatever)
MYMACRO(foo, bar);

if (whatever)
MYMACRO(foo, bar);
else
baz;

And there will be a (possibly obscure !) syntax error if the semi colon is
missing, as in your example:

MYMACRO(foo,bar ) // note no semicolon
baz();

- because it will expand to "true baz()" at the end.

The reason for using "true" as the null statement and not "0" is because
there is less chance of the statement still being valid without a semi
colon, eg. something beginning with "-" or "*".

Hope this helps - let me know if I've missed something !

David F


Jul 22 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
2992
by: Chris Reedy | last post by:
For everyone - Apologies for the length of this message. If you don't want to look at the long example, you can skip to the end of the message. And for the Python gurus among you, if you can spare the time, I would appreciate any comments (including words like evil and disgusting, if you think they are applicable :-}) on the example here. Kenny -
37
2814
by: michele.simionato | last post by:
Paul Rubin wrote: > How about macros? Some pretty horrible things have been done in C > programs with the C preprocessor. But there's a movememnt afloat to > add hygienic macros to Python. Got any thoughts about that? "Movement" seems quite an exaggeration. Maybe 2-3 people made some experiments, but nobody within the core Python developers seems to be willing to advocate the introduction of macros. > Why should you care whether the...
25
9139
by: Sabyasachi Basu | last post by:
While trying to port some stuff from Unix to Windows, I encountered a strange behaviour of function macros with empty arguments. Here is a small snippet which illustrates the problem: #include <iostream> #include <string> using namespace std; #define B(X, Y) Y
11
2857
by: Ben Hetland | last post by:
....in certain cituations they can be useful if not for anything else, then at least for saving a lot of repetetetetetitititive typing. :-) Beyond the point of "do something better instead", I'm curious about how the following syntactical problem can be solved. It should apply equally to C and C++ as it mainly is a preprocessor-related problem. I tryed to define something similar to the following example: ...
4
16759
by: DG | last post by:
Hi, Can anyone advise how to execute multiple statements in a single query batch. For example- update customers set customer_name = 'Smith' where customer_name = 'Smyth'; select * from customers; I can execute each statement individually but get the 'you have an error in
24
3652
by: sureshjayaram | last post by:
In some functions where i need to return multiple error codes at multiple places, I use multiple return statements. Say for ex. if (Found == 1) { if (val == -1) return error1; } else { if (val2 == -1)
4
1700
by: Chronologic | last post by:
All, I have an issue I would like some expert help on. I understand, or so I believe, that C# does not support the concept of a "compile time macro". At least not in the sense I'm looking for. While many users contend that macros are inherently evil, I would argue that no - they are not, they have a function. That function is sometimes -- perhaps much too often -- abused, but they do have a
7
13080
by: aaragon | last post by:
Hi everyone, I have a simple question. I'm trying to make a macro in one file so I can use it in main.cpp. The idea is that I the user of my code has simple to type the macro definition to replace a more complicated code. Something like the following: // file.h #define OBJECTIVE template <class T\ void operator()(T& chrom_,double* fitness_); // file main.cpp
20
3399
by: copx | last post by:
Is it true that C macros are unsafe when combined with side effects even if they are "clean" e.g. could foo_macro(++c); execute "++c" multiple times even if foo_macro is "clean"? I have always thought that "clean" macros (i.e. macros where all parameters are surrounded by parentheses in the definition) do not have this problem... I am wondering because I have just looked up putc() in a reference, and it
0
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9515
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10427
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10155
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5431
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.