assert-macro: brackets

L

Leo

Hi @ all.

I looked up the implementation of the assert macro of my compiler
(MinGW), because I wanna write my own assert.

I found this:

#define assert(x) ((void)0)
#define assert(e) ((e) ? (void)0 : _assert(#e, __FILE__, __LINE__))

My question is: Do the outer brackets have any reason? If yes, which?

Is this not equivalent to the above code?:

#define assert(x) (void)0
#define assert(e) (e) ? (void)0 : _assert(#e, __FILE__, __LINE__)
 
J

John Harrison

Hi @ all.

I looked up the implementation of the assert macro of my compiler
(MinGW), because I wanna write my own assert.

I found this:

#define assert(x) ((void)0)
#define assert(e) ((e) ? (void)0 : _assert(#e, __FILE__, __LINE__))

My question is: Do the outer brackets have any reason? If yes, which?

Is this not equivalent to the above code?:

#define assert(x) (void)0
#define assert(e) (e) ? (void)0 : _assert(#e, __FILE__, __LINE__)

No, try the following with your two versions of assert

if (0 && assert(0))
{
}

With the first definition this will not call _assert (which is correct),
with the second definition it will.

john
 
G

Gianni Mariani

John said:
....

No, try the following with your two versions of assert

if (0 && assert(0))

I think you meant

if (0 && assert(1))
{
}

With the first definition this will not call _assert (which is
correct), with the second definition it will.

G
 
L

Leo

John said:
No, try the following with your two versions of assert

if (0 && assert(0))
{
}

With the first definition this will not call _assert (which is
correct), with the second definition it will.

john

Both versions won't compile :D
 
J

John Harrison

Both versions won't compile :D

Yes, I realised that after I posted.

How about this?

1 && assert(0);

That fails to compile with version 1, but compiles with version 2.

I'm sure a better example could be devised, but the point is that the
extra bracket in the first version avoids any surprises.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top