Showing posts with label C #define. Show all posts
Showing posts with label C #define. Show all posts

Thursday, July 12, 2018

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Description

In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code.

Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions.

Syntax:





#define token value



Let's see an example of #define to define a constant.





#include <stdio.h>
#define PI 3.14
main()
{
printf("%f",PI);
}



Output:

3.140000

Let's see an example of #define to create a macro.





#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
void main() {
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}



Output:

Minimum between 10 and 20 is: 10

Parameterized Macros

One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number as follows −





int square(int x)
{
return x * x;
}



We can rewrite above the code using a macro as follows −





#define square(x) ((x) * (x))



Macros with arguments must be defined using the #define directive before they can be used. The argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between the macro name and open parenthesis. For example −





#include <stdio.h>

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

int main(void) {
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}



When the above code is compiled and executed, it produces the following result −

Max between 20 and 10 is 20




Instagram