2

i found this code from here

#if 1
#define rsAssert(v) do {if(!(v)) LOGE("rsAssert failed: %s, in %s at %i", #v, __FILE__, __LINE__);} while(0)
#else
#define rsAssert(v) while(0)
#endif

Question 1:

Here i am not getting why do and while is used here? Is there any special reason for using this?

Question 2:

What is the purpose of doing this all in macro. Why just one dont use assert() ?

i think perhaps there is a valid reason for this..

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222

3 Answers3

3

Your first question about why there's a do/while "loop" is covered here: What's the use of do while(0) when we define a macro?

The answer to the second question could be better answered by the code's author, but I guess they wanted to use their own logging system when an assert failed rather than the default one.

Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
2

The do/while is a well-known trick for turning a block of statements into something that syntactically acts like a single statement. It allows use in places like:

if (whatever)
    rsAssert(whatever);
else
    // ...

whereas, most alternatives would produce a syntax error in this case.

As for why using it at all: because it writes output with LOGE instead of printing to stderr, and (unless LOGE does so) this doesn't seem to abort the program like assert will.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

As asked many times before, the reason a do-while loop is use is for syntactic sugar:

// this line would be valid if a simple if was used:
rsAssert(myAssert)

// with a do-while, however, this is now invalid:
rsAssert(myAssert)

// so, that means you have to add the ';' to make it look like a function call:
rsAssert(myAssert);
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201