简体   繁体   中英

Difference between macros and Functions in C language

I'm new to C language. When I'm learning C language I learn something called macros. As I understood macros are like a functions in JavaScript that we can call when we needed. But then I learn that after compiling the program all the places that i have called to macros are replaced by the definition of the macro. So I'm confusing what is the difference between macro and a function in C language.

Also I wanna know whether I can write multi line macros in my code and if it is possible how it will be replaced when the code compiled.

As a example assume that I wanna macro to find the maximum value among two numbers .

Is it a good practice to write that process as a macro rather than write is as a function.

Everything stands - don't use macro . A better alternative inline the function - it would achieve the same efficiency you expect. But for fun, I worked a bit to use gcc statement expressions that means a non-portable gcc centric solution.

#include <stdio.h>
#define SUM(X)                           \
    ({  long s = 0;                      \
        long x = (X) > 0 ? (X) : (-(X)); \
        while(x) {                       \
            s += x % 10;                 \
            x /= 10;                     \
        }                                \
        s;                               \
    })
int main(void) {
    printf("%ld\n",SUM(13423) );
    return 0;
}

This solution begs for a function. Using statement expression to have that return something feature inside macro. Well I said, go for inline function. That would serve the purpose much cleaner way.

Using macros is sometimes dangourous: https://gcc.gnu.org/onlinedocs/cpp/Macro-Pitfalls.html#Macro-Pitfalls you can read on the dangers of using it here..

but, for your question:

#include <stdio.h>

#define SUM(X, Y) (X + Y)
void main() {
    printf("the sum of 3,4 is : %d\n", SUM(3,4));
}

will output:

the sum of 3,4 is : 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM