+ 4
[Solved] Macro vs function ???
Pls explain the result. I am much new to macro's or overloading in C. https://code.sololearn.com/cHMXTEK229jp/?ref=app
13 odpowiedzi
+ 4
hepy(z) (7*z)
y=2;
hepy(y+1);
the value pass to the macro will replace the expression
z=y+1
7*y+1;
y=2
7*2+1 //multiplication precede addition
14+1=15
+ 2
It's not operator overloading and there is no operator overloading in c. It's about macros.
+ 1
This is not called operator overloading though.
+ 1
Can we say that "hapy (z)" is a function, "z" is an argument, and "(7 * z)" is the return value?
+ 1
✳AsterisK✳ thank you. But why 7*z will transform to 7*y+1 while z = (y+1)? The case is what you wrote but I have little idea about macros (that's why I hate them).
Edit: Understood. Macro passes expressions as is unlike function.
So if I add one more () arround y+1, 21 is the result. Anyway thanks.
+ 1
To_be_unnamed(_?_^@%∞)
and yet the analogy with the function can be used. For example:
#include <stdio.h>
int macro(int z) {
return (z+1);
}
int main() {
int y=2;
printf("%d",macro(7*y));
return 0;
}
+ 1
what is the difference?
https://code.sololearn.com/cbrFD2qqFM64/?ref=app
Macros can be called as small functions that are not as overhead to process. If we have to write a function (having a small definition) that needs to be called recursively (again and again), then we should prefer a macro over a function.
+ 1
I seem to have found a solution, look at the code please
https://code.sololearn.com/cbrFD2qqFM64/?ref=app
+ 1
Difference.
https://code.sololearn.com/c2oE94SXX1e9/?ref=app
0
Sonic yeah it sould be macro
0
Alex Gyperkate if hapy(z) is a function then the result would be 21 not 15
0
Alex Gyperkate that's a different question.
0
This is elementary, but it is possible to make an analogy
The #define directive is used to create object-like macros for constants based on values or expressions.
#define can also be used to create function-like macros with arguments that will be replaced by the preprocessor.
A function:
• is a block of code that performs a specific task
• is reusable
• makes a program easier to test
• can be modified without changing the calling program