Macros Operations

#define

Macro Embedded C Interview Questions : 

Q1: What is a macro in C?

Ans: A macro is a preprocessor directive in C that defines a symbolic name or constant value that can be used throughout the program.

Q2: What is the syntax for defining a macro?

Ans: The syntax for defining a macro in C is as follows:

#define MACRO_NAME macro_value

Q3: What is the difference between a macro and a function in C?

Ans: A macro is a preprocessor directive that is expanded at compile time, while a function is a code block that is executed at runtime.

Q4: How to use a macro?

Ans: To use a macro in C, simply write its name wherever user want to use its value in the program.

Q5: What is the purpose of the #ifdef directive?

Ans: The #ifdef directive is used to check if a macro has been defined in the program. If the macro has been defined, the code block between #ifdef and #endif is executed.

Q6: What is the purpose of the #ifndef directive?

Ans: The #ifndef directive is used to check if a macro has not been defined in the program. If the macro has not been defined, the code block between #ifndef and #endif is executed.

Q7: What is the purpose of the #undef directive?

Ans: The #undef directive is used to undefine a macro that has been previously defined in the program.

Q8: What is the purpose of the #include directive?

Ans: The #include directive is used to include a header file in the program that contains declarations for functions, variables, and macros used in the program.

Q9: How to pass arguments to a macro?

Ans: Arguments can be passed to a macro by enclosing them in parentheses after the macro name. For example:

#define ADD(a, b) ((a) + (b))

Q10: How to concatenate strings in a macro?

Ans: Strings can be concatenated in a macro using the ## operator. For example:

#define CONCAT(a, b) (a##b)

Q11: Write a program to define a constant value using #define?
Ans: 

#include <stdio.h>
#define MAX 100

int main() 
{
    printf("The value of MAX is %d\n", MAX);
    return 0;
}

Q12: Write a program to define a macro that adds two numbers?
Ans: 

#include <stdio.h>
#define ADD(a, b) ((a) + (b))

int main() 
{
    int num1 = 10, num2 = 20, sum;
    sum = ADD(num1, num2);
    printf("The value of sum is %d\n", sum);
    return 0;
}
    

Q13: Write a program to define a macro that calculates the square of a number?
Ans: 

#include <stdio.h>
#define SQUARE(x) ((x) * (x))

int main() 
{
    int num = 5, sq;
    sq = SQUARE(num);
    printf("The square of %d is %d\n", num, sq);
    return 0;
}