Re: [cc65] Feature request: default arguments for functions.

From: Ullrich von Bassewitz <uz1musoftware.de>
Date: 2009-07-27 21:31:17
On Mon, Jul 27, 2009 at 05:20:45PM +0200, Groepaz wrote:
> shouldnt it be possible to implement the function using variadic args and
> pretty much get the desired behaviour like this?

variadic arguments aren't type save and must rely on one of the fixed
arguments to determine the variadic ones.

There's a special variable generated by cc65 for each function, that may be
used: __argsize__ contains the total size of the arguments passed to a
function. It is a constant if the function is non variadic and resolves to a
variable access in variadic function. A function with a default argument could
be written as

        void foo (int a, ...)
        /* Can also be called as foo(int a, int b). If b is not given, it
         * defaults to zero.
         */
        {
            int b;
            va_list ap;
            switch (__argsize__) {

                case sizeof (a):
                    /* b was not given so use zero */
                    b = 0;
                    break;

                case sizeof (a) + sizeof (int):
                    /* Access the real b */
                    ap = va_start (a);
                    b = va_arg (ap, int);
                    va_end (ap);
                    break;

                default:
                    /* OOPS - wrong number of args */
                    fatal_failure ("Programmer is a jerk!");
            }

            ...
        }

As you can see, this method has quite some drawbacks: Larger code, missing
type safety and lack of portability are just some of them. However, there may
be situations where the feature comes handy. As an example, the POSIX open()
function is implemented in this way.

Regards


        Uz


-- 
Ullrich von Bassewitz                                  uz@musoftware.de
----------------------------------------------------------------------
To unsubscribe from the list send mail to majordomo@musoftware.de with
the string "unsubscribe cc65" in the body(!) of the mail.
Received on Mon Jul 27 21:34:01 2009

This archive was generated by hypermail 2.1.8 : 2009-07-27 21:34:02 CEST