Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function-like macro definition in C

I'd like to define a function like MACRO . i.e.

#define foo(x)\
#if x>32\
 x\
#else\
 (2*x)\
#endif

that is,

if x>32, then foo(x) present x
else, foo(x) present (2*x)

but my GCC complains about:

int a = foo(31);

I think C preprocessor should be handle this correctly. since at compile time, it knows x=33. it could replace foo(33) with (2*33)

like image 674
richard Avatar asked Jul 09 '10 17:07

richard


People also ask

Can a function defined as macro?

Macros are generally used to define constant values that are being used repeatedly in program. Macros can even accept arguments and such macros are known as function-like macros. It can be useful if tokens are concatenated into code to simplify some complex declarations.

What is a macro definition in C?

Macros and its types in C/C++ A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro.

What is #define in C called?

The #define creates a macro, which is the association of an identifier or parameterized identifier with a token string. After the macro is defined, the compiler can substitute the token string for each occurrence of the identifier in the source file.

What is difference between macro and inline function in C?

The basic difference between inline and macro is that an inline functions are parsed by the compiler whereas, the macros in a program are expanded by preprocessor. The keyword used to define an inline function is “inline” whereas, the keyword used to define a macro is “#define“.


1 Answers

You can as follows

#define foo(x) ((x) > 32 ? (x) : (2 * (x)))

But that evaluates x multiple times. You can instead create a static function, which is cleaner

static int foo(int x) {
  if(x > 32) 
    return x;
  return 2 * x;
}

Then you are also able to pass things to foo that have side effects, and have the side effect happen only one time.

What you have written is using the #if, #else and #endif preprocessor directives, but you need to use language constructs if you pass variables to the macro and want to evaluate their values. Using if, and else statements as in the actual language constructs don't work either, because control flow statements don't evaluate to values. In other words, an if statement is steering control flow only ("if A, then execute B, else execute C"), not evaluating to any values.

like image 73
Johannes Schaub - litb Avatar answered Oct 01 '22 01:10

Johannes Schaub - litb