Search code examples
cargumentsheader-filesdeclaration

What is the purpose of declaring an n-ary function twice, such that the order of the arguments of the second is the reverse of the first?


I was reading through a C header file containing function prototypes of the API for a particular real-time operating system (RTOS), and noticed that most of the functions are declared in the following manners:

#define foo(arg_1, arg_2, ... arg_n)        foo(arg_n, ... arg_2, arg_1)

That is, functions with 2 or more arguments are declared pairwise as shown, in which the order of arguments of the second function is the reverse of that of the first function.

May I know what is the purpose of doing so?


Edit:

I dug further into the code and found that this header file and some other header files contain macros to support different C/C++ compilers. In particular, the calling convention _pascal is invoked if the Microsoft C/C++ compiler is used. In this case, the API functions are declared pairwise as stated in the problem description above.

I believe both JeremyP and Frankie_C deserve kudos for correctly guessing the purpose, despite the lack of context. The keyword "calling convention" is of great help to me and pivotal in my attempt to understand that segment of code.


Solution

  • It seem an header crafted to interface an object library wrote for PASCAL calling convention, where the parameters pushing on the stack is reversed.

    In C historic ABI convention the parameters were pushed onto the stack from right to left order.

    In Pascal, that didn't supported variadic functions, the arguments were pushed left to right.

    The define reverse the order fixing the ABI.

    See https://azrael.digipen.edu/~mmead/www/Courses/CS225/HistoryOfCallingConventions.html