Search code examples
ccompiler-constructionprintfprogramming-languages

How to resolve variable number of arguments problem of printf if reverse printing is not allowed


I am taking a course about language design and this particular question has to do with how printf in C deal with issue of variable number of arguments. In essence, I learned that printf would push arguments from the last one all the way to the format string which stores information about offsets so that the frame pointer would find the format string and then use the offset derived from the format string to find arguments' offsets.

But the question I have asks for another way to deal with this problem when reversing of arguments is not allowed. This confuses me. For now, my approach is move the frame pointer to the lowest point of the runtime stack so that it finds format string and offsets to the actuals are positive.

Please advise


Solution

  • If you were to design a new compiler for a different calling convention, you could have the compiler push the number of actual arguments with which the call was done, or set that number in a specific register such as RAX/EAX, which will be overridden anyway.

    Another option would be to redefine the printf() API to have the format string as the last parameter. In this way you will have all you need to access the stack looking for your parameters.