+ 1
What is Macro in C?
I am in need of a brief explanation about Macro from C programming language.
10 Answers
+ 5
Md. Tokee Tahmid
The macro in C language is known as the piece of code which can be replaced by the macro value. The macro is defined with the help of #define preprocessor directive and the macro doesnât end with a semicolon(;).
example: #define PI 3.14
#define - Preprocessor Directive
PI - Macro Name
3.14 - Macro Value
then if we want to use it in the code we only replace The macro name ("PI")With the macro value 3.14 like this
printf("%f",2*PI*5); //2*3.14*5
+ 5
We can define macros with different datatypes as following but we can't use the same macro names for 2 different values
#define MAX 100
#define MIN 1
#define GRAVITY 9.8
#define NAME "Scaler"
#define NAME "Vector" //error
#define TRUE 1
#define FALSE 0
+ 4
function-like macro in C
#define Area(r) (PI*(r*r))
The macro name is Area which takes the argument r .then we call it like this
float radius = 2.5;
printf("Area of circle is %f", Area(radius));
At the time of preprocessing the value Area(radius) gets replaced with the processed macro value
// PI*2.2*2.5 =3.14*2.5*2.5
+ 2
include <whatever>
#define VALUE 5 // <---- Thats a macro
...
You can set values and even functions to a macro and they just replace the macro keyword with the value given throught the program before it runs
+ 2
Be careful with macros as a function:
#include <stdio.h>
#define POWER(x) x * x
int pwr(int x){
return x * x;
}
int main(void){
printf("POWER(x) = %d\n", POWER(2 + 3));
printf("pwr(x) = %d\n", pwr(2 + 3));
puts("Because the macro places x * x == 2 + 3 * 2 + 3");
puts("And pwr(x) == 2 + 3 == 5 == 5 * 5");
return 0;
}
output:
POWER(x) = 11
pwr(x) = 25
Because the macro places x * x == 2 + 3 * 2 + 3
And pwr(x) == 2 + 3 == 5 == 5 * 5
+ 2
The macro in C language is a segment of code which is replaced by a value of the macro. Macro is define bu #define preprocessor directive.
Ex: #define PI 3.14
+ 2
Nadhil An
remove semi colon after if(num<0)
+ 1
Aly Alsayed beware that your macro function example has a bug. If the code uses Area(x + y), the macro would get substituted as (PI*(x + y*x + y)) and give undesired results.
Always surround macro parameters with parentheses, as well as the whole macro, itself: (PI*(r)*(r)).
+ 1
Nadhil An
edit
if(num1>num2)
printf("greater number is %d", num1);
}else{
printf("greater number is %d", num2);
}
+ 1
Aly Alsayed & Nadhil An please don't hijack other questions. Move your responses to https://www.sololearn.com/Discuss/3055491/?ref=app