2

I have been wondering how C's printf function worked, so I decided to look at gcc's stdio.h for the definition. To my surprise, the printf function in gcc is defined with the arguments "const char*, . . . ". I tried doing this for myself, in a simple program that I made.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int Print(const char *text, ...) {

    printf("%s\n", text);
}

int main() {
    Print("Hello, World!", "a");
}

I can pass however many arguments I want into it, even though those arguments won't have any future access point. I am wondering more about this, and I wish to know if anybody has more information.

TheDude04
  • 107
  • 9
  • [C Variadic functions](https://en.cppreference.com/w/c/variadic). Most C reference texts will include a section on how they work, and how the variadic arguments list macros are used in their conjunction. – WhozCraig Apr 07 '21 at 13:30
  • They are called [variadic functions](https://en.cppreference.com/w/c/variadic) and their arguments can be handled using the `va_*` functions. – axiac Apr 07 '21 at 13:30
  • Also related: [Technically, how do variadic functions work? How does printf work?](https://stackoverflow.com/questions/23104628/) – Brian61354270 Apr 07 '21 at 13:32

1 Answers1

1

This is how ISO C defines a syntax for declaring a function to take a variable number or type of arguments. Using ... notation with stdarg.h you can implement variadic funtion: functions that accept an unlimited number of argument. Its usage is explained in Gnu library manual.

You can go through the parameters using va_args from stdarg.h. Here is good tutorial to start with.

You can also implement variadic macros SOME_MACRO(...). For that you can refer to this thread.

SOFuser
  • 134
  • 1
  • 10