473,772 Members | 2,391 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Variadic functions

Do variadic functions (such as printf()) always scan the format string
for format specifiers, even when there are no additional arguments?
If it is instead a QoI issue, what would be true for a typical
implementation?

Basically, I'm wondering whether there is any advantage to using
puts() instead of printf() for output of a string.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #1
5 2167
Christopher Benson-Manica wrote:
Do variadic functions (such as printf()) always scan the format string
for format specifiers, even when there are no additional arguments?
If it is instead a QoI issue, what would be true for a typical
implementation?

Basically, I'm wondering whether there is any advantage to using
puts() instead of printf() for output of a string.


In general case functions have no means to determine how many arguments
was supplied in the call. In other words, the situation "when there are
no additional arguments" is not detectable from inside of the function,
which means that the function has no other choice but to scan the format
string and try to retrieve the variadic parameters (if format string
directs it to do so). If there were no actual arguments in the call, the
behavior is undefined.

--
Best regards,
Andrey Tarasevich
Nov 14 '05 #2
>Do variadic functions (such as printf()) always scan the format string
for format specifiers, even when there are no additional arguments?
There is no standard way for a varadic function to know how many
arguments it actually got. Now, printf() *COULD* be implemented
with compiler magic, but I can't see where this particular optimization
is worth doing. And printf() would STILL have to translate %% in
the format string to % in the output.
If it is instead a QoI issue, what would be true for a typical
implementation ?
In a typical implementation, printf() does not know how many arguments
it actually got, and the way it tells how many arguments it's
supposed to have is to scan the format string.
Basically, I'm wondering whether there is any advantage to using
puts() instead of printf() for output of a string.


printf(string) and puts(string) are not equivalent. puts() adds a
trailing newline; printf() does not. printf(string) is downright
dangerous if string can contain arbitrary data obtained from input
that hasn't been screened for % characters (funny input can make
the program smegfault). printf("%s\n", string) is equivalent to
puts(string) when the return value is not used, but this doesn't
involve invoking printf() with no arguments beyond the format string.

Any program can run infinitely fast if it's acceptable for it to
give the wrong (no) result.

Gordon L. Burditt
Nov 14 '05 #3
In article <cm**********@c hessie.cirr.com >,
Christopher Benson-Manica <at***@nospam.c yberspace.org> wrote:
Do variadic functions (such as printf()) always scan the format string
for format specifiers, even when there are no additional arguments?
If it is instead a QoI issue, what would be true for a typical
implementation ?
Mu. Barring implementation magic in printf, the only way it has to
tell that there are(should be) no additional arguments is to scan the
format string. In the general case, a variadic function needs to be
able to determine the availability and type of variadic arguments using
only information in the non-variadic arguments.
Basically, I'm wondering whether there is any advantage to using
puts() instead of printf() for output of a string.


puts() handles '%' in the string rather more nicely, by simply printing
it instead of invoking undefined behavior. It also appends a newline,
which may be undesirable.
If you can get away with not using printf *at all*, you can avoid bringing
the entire printf engine into your program. Using printf somewhere means
using it somewhere else has no additional size cost. Linking against
dynamic libraries will make this potential benefit irrelevant.
Using printf will have a penalty of maybe a few cycles per character
for strings that don't contain any '%'. With the additional cost of
actually moving the characters between the program and whatever stdout
is connected to, there's no way you'll ever notice this cost, no matter
how many characters you're printing.

printf("%s\n",s tr) behaves exactly the same as puts(str). If the trailing
newline is undesirable and str may contain '%', you want printf("%s",str ).
dave

--
Dave Vandervies dj******@csclub .uwaterloo.ca
I'm ashamed to admit it, but I actually thought of this possibility when
writing the code shown. That means I've been hanging around comp.lang.c
*much* too long. --Eric Sosman in comp.lang.c
Nov 14 '05 #4
Christopher Benson-Manica wrote:

Do variadic functions (such as printf()) always scan the format string
for format specifiers, even when there are no additional arguments?
If it is instead a QoI issue, what would be true for a typical
implementation?

Basically, I'm wondering whether there is any advantage to using
puts() instead of printf() for output of a string.


K&R2, section 7.7, page 156,
shows a function definition for minprintf().
It should give you some idea of the logic invlolved.
The logic of puts is relatively simple.

In my toy library, I have put_s like this:

#include <stdio.h>
#define put_c(c, stream) (putc((c), (stream)))
#define put_char(c) (put_c((c), stdout))

int put_s(const char *s)
{
while (*s != '\0') {
if (put_char(*s) == EOF && ferror(stdout) != 0) {
return EOF;
}
++s;
}
return put_char('\n');
}

My min_printf is like this:

#include <stdarg.h>

#define fsput_char(c) \
(put_char(c) == EOF && ferror(stdout) != 0 ? EOF : 1)

static int fsput_s(const char *);
static int fsput_u(unsigne d);
static int fsput_u_plus_1( unsigned);
static int fsput_d(int);

int min_printf(cons t char *s, ...)
{
int count, increment;
va_list ap;

va_start(ap, s);
for (count = 0; *s != '\0'; ++s) {
if (*s == '%') {
switch (*++s) {
case 'c':
increment = fsput_char(va_a rg(ap, int));
break;
case 'd':
increment = fsput_d(va_arg( ap, int));
break;
case 's':
increment = fsput_s(va_arg( ap, char *));
break;
case 'u':
increment = fsput_u(va_arg( ap, unsigned));
break;
default:
increment = fsput_char(*s);
break;
}
} else {
increment = fsput_char(*s);
}
if (increment != EOF) {
count += increment;
} else {
count = EOF;
break;
}
}
va_end(ap);
return count;
}

static int fsput_s(const char *s)
{
int count;

for (count = 0; *s != '\0'; ++s) {
if (put_char(*s) == EOF && ferror(stdout) != 0) {
return EOF;
}
++count;
}
return count;
}

static int fsput_u(unsigne d integer)
{
int count;
unsigned digit, tenth;

tenth = integer / 10;
digit = integer - 10 * tenth + '0';
count = tenth != 0 ? fsput_u(tenth) : 0;
return count != EOF && put_char(digit) != EOF ? count + 1 : EOF;
}

static int fsput_u_plus_1( unsigned integer)
{
int count;
unsigned digit, tenth;

tenth = integer / 10;
digit = integer - 10 * tenth + '0';
if (digit == '9') {
if (tenth != 0) {
count = fsput_u_plus_1( tenth);
} else {
count = put_char('1') == EOF ? EOF : 1;
}
digit = '0';
} else {
count = tenth != 0 ? fsput_u(tenth) : 0;
++digit;
}
return count != EOF && put_char(digit) != EOF ? count + 1 : EOF;
}

static int fsput_d(int integer)
{
int count;

if (0 > integer) {
if (put_char('-') == EOF) {
return EOF;
}
count = fsput_u_plus_1(-(integer + 1));
return count != EOF ? count + 1 : EOF;
} else {
return fsput_u(integer );
}
}

--
pete
Nov 14 '05 #5
In <cm**********@c hessie.cirr.com > Christopher Benson-Manica <at***@nospam.c yberspace.org> writes:
Do variadic functions (such as printf()) always scan the format string
for format specifiers, even when there are no additional arguments?
If it is instead a QoI issue, what would be true for a typical
implementation ?
The only source of information WRT the number and type of arguments for
printf and friends is the format string. It is OK to pass them more
arguments than specified by the format string (they will ignore them)
but it invokes undefined behaviour to pass them fewer arguments.
Basically, I'm wondering whether there is any advantage to using
puts() instead of printf() for output of a string.


Yes: puts doesn't have to scan the string (except for finding
the terminating null character) and you don't have to tread the %
character in a special way. As an added bonus, it also appends a
free newline at the end of the string (use fputs if you don't want it).

OTOH, the program is (slightly) more readable if printf is the only
output function being used.

However, both pro and con arguments are extremely weak, so use whatever
you feel as the most appropriate to the context.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1895
by: Loony | last post by:
Hi, I want to use variadic functions with stl containers as arguments but I am not sure if that is possible and if so how. I'm using gcc 3.3 on Suse 8.2 Hope someone can help me. Thanx in advance
3
3550
by: Loony | last post by:
Hi, I have a problem with my code. I am using a virtual class in which I define a variadic function. This class is inherited by another one which then implements it. The problem occurs while linking: undefined reference to `vtable undefined reference to `typeinfo I'm using gcc 3.3 to compile the code.
89
6533
by: Sweety | last post by:
hi, Is main function address is 657. its show in all compiler. try it & say why? bye,
19
4260
by: Ross A. Finlayson | last post by:
Hi, I hope you can help me understand the varargs facility. Say I am programming in ISO C including stdarg.h and I declare a function as so: void log_printf(const char* logfilename, const char* formatter, ...); Then, I want to call it as so:
2
2925
by: Florian G. Pflug | last post by:
Hi I faintly remember that I once stumbled upon a way to declare variadic functions (functions that take a variable number of arguments) in plpgsql - but I just searched the docs and can't find any reference to variadic functions. So - please enlighten me - are there variadic functions in plpgsql, or are there none?
9
3277
by: CryptiqueGuy | last post by:
Consider the variadic function with the following prototype: int foo(int num,...); Here 'num' specifies the number of arguments, and assume that all the arguments that should be passed to this function are of type int. (My question has nothing to do with the definition of the function foo, so don't bother about it.) If I call the function as: foo(2,3,4,5,6,7,8);/*More arguments than expected*/
4
3642
by: Boltar | last post by:
Hi Is it possible to nest variadic functions? Eg to do something like this: void mainfunc(char *fmt, ...) { va_list args; va_start(args,fmt);
4
4944
by: Boltar | last post by:
Hi I think I posted a question similar to this on here a while back but I can't find the thread and I need something more general anyway. My problem is I have 2 variadic functions , one of which needs to call the other passing its entire argument list but the other needs to be callable from anywhere else in the program as a variadic too, ie it *can't* have va_list as a paramater type.
8
3454
by: Christof Warlich | last post by:
Hi, is there any way to access individual elements in the body of a variadic macro? I only found __VA_ARGS__, which always expands to the complete list. Thanks for any help, Christof
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10261
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9911
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8934
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6713
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.