﻿ C – Macro to find maximum/minimum of two numbers

C Language: C program to define Macro to find maximum/minimum of two numbers

C – Macro to find maximum/minimum of two numbers.

In computer programming, a macro is a rule or pattern that specifies how a certain input should be mapped to a replacement output. Applying a macro to an input is known as macro expansion.

Here are the macros for maximum and minimum:

#define MAX(x, y) ((x) > (y) ? (x) : (y))

#define MIN(x, y) ((x) < (y) ? (x) : (y))

Example:

Code:

``````# include <stdio.h>

#define MAX(x, y) ((x) > (y) ? (x) : (y))
#define MIN(x, y) ((x) < (y) ? (x) : (y))

int main() {
int a = 45, b = 34;
printf("The Maximum of %d and %d is %d\n", a, b, MAX(a, b));
printf("The Minimum of %d and %d is %d\n", a, b, MIN(a, b));
return 0;
}
``````

Output:

```The Maximum of 45 and 34 is 45
The Minimum of 45 and 34 is 34
```

In the above code, the MAX and MIN macros are defined using the ternary operator to check which of the two numbers is larger or smaller. The macros take two arguments x and y, representing the two numbers to be compared.

The main() function calls the macros with two integer values a and b, and the results are printed to the console.

﻿

C Programming: Tips of the Day

C Programming - How do you pass a function as a parameter in C?

Declaration

A prototype for a function which takes a function parameter looks like the following:

```void func ( void (*f)(int) );
```

This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:

```void print ( int x ) {
printf("%d\n", x);
}
```

Function Call

When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:

```func(print);
```

would call func, passing the print function to it.

Function Body

As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:

```for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
```

Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:

```void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
```

Ref : https://bit.ly/3skw9Um