Path: ...!feeds.phibee-telecom.net!2.eu.feeder.erje.net!feeder.erje.net!fu-berlin.de!uni-berlin.de!not-for-mail From: ram@zedat.fu-berlin.de (Stefan Ram) Newsgroups: comp.lang.c Subject: Re: is it possible to have functions with 0, 1, or 2 args? Date: 5 Aug 2024 09:06:42 GMT Organization: Stefan Ram Lines: 46 Expires: 1 Jul 2025 11:59:58 GMT Message-ID: References: <7q-dnbTDU4oBES37nZ2dnZfqnPednZ2d@brightview.co.uk> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Trace: news.uni-berlin.de G2pQCYPAS7CaVow6V9hBpQxsk7EHmyfHYt0BOO/lQREsIr Cancel-Lock: sha1:H9/UhSU6kOZuPJkCIf1WVco3BKM= sha256:t3OHSZAWw0Z41rbi45N9NiHrn2XPbO0yQCHAeHEzLBw= X-Copyright: (C) Copyright 2024 Stefan Ram. All rights reserved. Distribution through any means other than regular usenet channels is forbidden. It is forbidden to publish this article in the Web, to change URIs of this article into links, and to transfer the body without this notice, but quotations of parts in other Usenet posts are allowed. X-No-Archive: Yes Archive: no X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some services to mirror the article in the web. But the article may be kept on a Usenet archive server with only NNTP access. X-No-Html: yes Content-Language: en-US Bytes: 3232 Mark Summerfield wrote or quoted: >The rational is that I'd like to create a function `new_thing()` which >takes an optional size, e.g., I'm hella stoked on writing code that's chill in C. So, in a sitch like this, I might roll with a function that's /always/ down to take an argument and just hit it with a "-1" if I'm not trying to lock down a size. The "va_list" jazz in C, courtesy of the header, lets functions roll with a flexible number of args. It's like a buffet line for arguments, where you can scoop them up one by one using those gnarly macros "va_start", "va_arg", and "va_end". But here's the rub - the function's not psychic, so it can't just divine how many args are coming down the pike. You got to clue it in somehow, like passing a head count or dropping a hint about where to pump the brakes. The coder doesn't have to play bean counter though; he could just slap a "Dead End" sign at the tail of the arg parade! main.c #include #include int f( int const n, ... ) { va_list args; /* to hold the variable arguments */ va_start( args, n ); /* Initialize the "va_list" variable with the */ int result; /* variable arguments, starting after n */ switch( n ) { case 0: result = f( 2, 3, 11 ); break; /* va_arg(args, int) retrieves the next argument from the "va_list" of type "int" */ case 1: result = f( 2, 3, va_arg( args, int )); break; case 2: result = va_arg( args, int )+ va_arg( args, int ); break; } va_end( args ); /* Clean up the "va_list" */ return result; } int main( void ) { printf ( "%d\n", 14 == f( 0 )&& 8 == f( 1, 5 )&& 11 == f( 2, 2, 9 )); } transcript 1