【Macro definition】——Get the Nth parameter of the macro, and discard the redundant parameters

Function Description

Get the Nth parameter of the macro, and discard the extra parameters

accomplish

#define _GET_3RD_ARG(arg1, arg2, arg3, ...) arg3
#define _GET_4TH_ARG(arg1, arg2, arg3, arg4, ...)  arg4

_GET_3RD_ARG(1, 2)compile error

_GET_3RD_ARG(2, 1, 30)return 30

_GET_3RD_ARG(1, 2, 50, 60, 70)return 50

example

#include <stdio.h>

#define _GET_3RD_ARG(arg1, arg2, arg3, ...) arg3

int main()
{
    
    
    int num1 = 10;
    int num2 = 20;

    int result = _GET_3RD_ARG(num1, num2, 30);     // 获取第三个参数
    printf("Result: %d\n", result);                // 输出结果:30
    result = _GET_3RD_ARG(num1, num2, 40, 50, 60); // 参数多余三个参数,只获取第三个参数
    printf("Result: %d\n", result);                // 输出结果:40

    return 0;
}

result print

Result: 30
Result: 40

analyze

This macro is relatively simple

  • arg1 arg2 arg3 placeholders, indicating that there must be at least 3 parameters
  • ...This feature, means that redundant parameters are ...absorbed by

Guess you like

Origin blog.csdn.net/tyustli/article/details/132008878