Home > database >  What are the methods to define a inline replacement in code?
What are the methods to define a inline replacement in code?

Time:11-24

I want to define (var-1) > 0? var - 1: 0 as a inline replace. such as

#define MAX(VAR) as (VAR-1) > 0? VAR- 1: 0

like using etc?

CodePudding user response:

You define a function, and leave it up to the implementation to appropriately inline it.

 constexpr int max(int var) { return (var - 1) > 0 ? (var - 1) : 0; }

Aside: max isn't a great name for this, I'd suggest something like clamp_positive

CodePudding user response:

You can use, well, the inline keyword:

inline int max(int var) 
{ 
    return (var - 1) > 0 ? (var - 1) : 0; 
}

But, this will not force the inline, it will just suggest the compiler that you should make this function inline. The compiler can refuse your suggest, or make it inline even if you don't use the inline keyword

CodePudding user response:

The syntax is of #defines for preprocessors are simply

#define Name(...args) (replacement)

without as or =

So your definition would be

#define MAX(VAR) (VAR-1) > 0? VAR- 1: 0

In my experience I always find that it is useful to wrap defines like these with parenthesis to avoid ambiguity, you never know where this will be replace for instance MAX(x)*5 would give (x-1) > 0 ? x-1 : 0*5 that is the same as MAX(x).

#define MAX(VAR) ((VAR-1) > 0? VAR- 1: 0)

If you want to use a function as in suggested in the comments

int MAX(int v){
  return (v-1)>0? v-1:0;
}

Or as a template function

template<typename Tp>
Tp MAX(const _Tp &v){
  return (v-1)>0? v-1:0;
}
  •  Tags:  
  • c
  • Related