write a macro basic program in c

28 Dec 2022 Balmiki Mandal 0 C Programming

Micro Simple Program

In C, a macro is a preprocessor directive that allows you to define a shorthand notation for a sequence of instructions or expressions. Macros are defined using the #define directive and can be used to simplify repetitive code, define constants, or implement conditional compilation.

Here is a simple macro basic program in C:

C Programming
#define PRINT_MSG(msg) printf("%s\n", msg)

int main() {
  PRINT_MSG("Hello, world!");

  return 0;
}

This program defines a macro called PRINT_MSG(), which takes a string as input and prints it to the console. The main function then uses the PRINT_MSG() macro to print the message "Hello, world!" to the console.

When the program is compiled, the preprocessor will replace all instances of the PRINT_MSG() macro with its definition. This means that the following code:

C program
PRINT_MSG("Hello, world!");

is equivalent to the following code:

C program
printf("%s\n", "Hello, world!");

Macros can be used to make our code more concise and readable. For example, we can use a macro to define a common function call, or to print a message to the console. However, it is important to use macros carefully, as they can also make our code more difficult to debug.

Here is an example of a more complex macro basic program in C:

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

int main() {
  int num1, num2, max;

  printf("Enter two numbers: ");
  scanf("%d %d", &num1, &num2);

  max = MAX(num1, num2);

  printf("The biggest of %d and %d is %d\n", num1, num2, max);

  return 0;
}

This program defines a macro called MAX(), which takes two numbers as input and returns the bigger of the two numbers. The main function then uses the MAX() macro to find the biggest of two numbers that are entered by the user.

This program is more complex than the previous example, but it still uses macros to make the code more concise and readable. For example, the following code:

C program
max = MAX(num1, num2);

is equivalent to the following code:

C Program
if (num1 > num2) {
  max = num1;
} else {
  max = num2;
}
 Macros can be a powerful tool for writing C code, but it is important to use them carefully.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.