How does the particular C function work?

后端 未结 3 1489
南旧
南旧 2021-02-03 12:03

I am trying to learn C and am very confused already.

In the OOP languages i have used there exists the ability to perform method overloading, where the same function cou

3条回答
  •  借酒劲吻你
    2021-02-03 12:43

    C supports a type of function signature called "varargs" meaning "variable (number of) arguments". Such a function must have at least one required argument. In the case of printf, the format string is a required argument.

    Generally, on a stack-based machine, when you call any C function, the arguments are pushed onto the stack from right-to-left. In this way, the first argument to the function is that found on the "top" of the stack, just after the return address.

    There are C macros defined which allow you to retrieve the variable arguments.

    The key points are:

    • There is no type-safety for the variable arguments. In the case of printf(), if the format string is wrong, the code will read invalid results from memory, possibly crashing.
    • The variable arguments are read through a pointer which is incremented through the memory containing those arguments.
    • The argument pointer must be initialized with va_start, incremented with va_arg, and released with va_end.

    I have posted a ton of code you may find interesting on the related question:

    Best Way to Store a va_list for Later Use in C/C++

    Here's a skeleton of a printf() which only formats integers ("%d"):

    int printf( const char * fmt, ... )
    {
        int d;  /* Used to store any int arguments. */
        va_list args;  /* Used as a pointer to the next variable argument. */
    
        va_start( args, fmt );  /* Initialize the pointer to arguments. */
    
        while (*fmt)
        {
            if ('%' == *fmt)
            {
                fmt ++;
    
                switch (*fmt)
                {
                     case 'd':  /* Format string says 'd'. */
                                /* ASSUME there is an integer at the args pointer. */
    
                         d = va_arg( args, int);
                         /* Print the integer stored in d... */
                         break;
                 }
            }
            else 
               /* Not a format character, copy it to output. */
            fmt++;
        }
    
        va_end( args );
    }
    

提交回复
热议问题