WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C · Intermediate · question 33 of 100

What is a macro, and how do you define one in C? What are its advantages and disadvantages?

📕 Buy this interview preparation book: 100 C questions & answers — PDF + EPUB for $5

In C programming language, a macro is a preprocessor directive that allows programmers to define a shorthand notation for a sequence of instructions. A macro is a text substitution performed by the preprocessor before the code is compiled. Macros can be used to simplify code, reduce redundancy, and improve readability.

Macros are defined using the #define directive, which has the following syntax:

    #define macro_name(expression)

Here, macro_name is the name of the macro, and expression is the sequence of instructions that will be substituted whenever the macro is invoked.

Here is an example of defining a macro:

    #define SQUARE(x) ((x) * (x))

In this example, the SQUARE macro takes a single argument x and calculates the square of the argument by multiplying it with itself.

The main advantages of using macros are:

Code reduction: Macros allow programmers to reduce the amount of code they need to write by defining a shorthand notation for frequently used expressions.

Increased readability: Macros can improve the readability of code by providing descriptive names for complex expressions.

Flexibility: Macros can be used to customize code for different platforms, architectures, or compilers.

However, macros have some disadvantages as well:

Debugging: Macros can be difficult to debug because they are substituted before the code is compiled, making it harder to track errors.

Scoping: Macros do not respect the scoping rules of the programming language, which can lead to unintended side effects if the same macro name is used in different parts of the code.

Evaluation: Macros can evaluate their arguments multiple times, which can lead to unexpected behavior if the arguments have side effects.

It is important to use macros judiciously and follow best practices to avoid unintended consequences. Some best practices for using macros include using descriptive names, avoiding complex expressions, and encapsulating expressions in parentheses to avoid operator precedence issues.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C interview — then scores it.
📞 Practice C — free 15 min
📕 Buy this interview preparation book: 100 C questions & answers — PDF + EPUB for $5

All 100 C questions · All topics