Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have macro 'return' a value

Tags:

I'm using a macro and I think it works fine -

 #define CStrNullLastNL(str) {char* nl=strrchr(str,'\n'); if(nl){*nl=0;}} 

So it works to zero out the last newline in a string, really its used to chop off the linebreak when it gets left on by fgets.

So, I'm wondering if I can "return" a value from the macro, so it can be called like

 func( CStrNullLastNL( cstr ) ) ; 

Or will I have to write a function

like image 700
bobobobo Avatar asked Apr 20 '10 22:04

bobobobo


People also ask

Can a macro return a value?

Macros just perform textual substitution. They can't return anything - they are not functions.

How do I return a value from a macro in SAS?

A macro that returns a value must have exactly one statement that either is not a macro syntax statement, or is a macro syntax statement that returns a value into the processing stream. %sysfunc is an example of a statement that does so. Things like %let , %put , %if , etc.

How do I find the value of a macro?

There is no way you can test whether a defined macro has a value. You can only test whether a specific value matches the value of a macro. Any macro name that you define should always have a value, or it should never have a value.


2 Answers

For a macro to "return a value", the macro itself has to be an expression. Your macro is a statement block, which cannot evaluate to an expression.

You really ought to write an inline function. It will be just as fast and far more maintainable.

like image 187
Mike DeSimone Avatar answered Sep 22 '22 04:09

Mike DeSimone


#define CStrNullLastNL(str) ({ \     char* nl=strrchr(str,'\n');\     if(nl){*nl=0;} \     nl; \ }) 

should work.

Edit: ... in GCC.

like image 38
Danvil Avatar answered Sep 22 '22 04:09

Danvil