printf() with too many args -- legal? | Bytes (2024)

Kenneth Brody

I know that passing printf() too few arguments, or arguments of the wrong
type invokes UB. However, what about passing too many arguments, if the
expected arguments are of the correct type?

For example:

char format1[] = "foo %s bar %s baz %d";
char format2[] = "foo %s bar %s no baz here";

char *strvar1 = "one", *strvar2 = "two";
int intvar = 123;

....

printf( some_condition ? format1 : format2, strvar1, strvar2, intvar );

When "some_condition " is false, printf() will expect two strings, but will
be passed two strings and an int.

Yes, I know this can be rewritten as:

if ( some_condition )
printf(format1, strvar1,strvar2 ,intvar);
else
printf(format2, strvar1,strvar2 );

However, this construct appears in numerous places throughout existing
code, which works on all current platforms it's ported to. I'd like to
make sure that it won't cause problems on some future platform.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Nov 15 '05

Subscribe Reply

33 printf() with too many args -- legal? | Bytes (1) 5938 printf() with too many args -- legal? | Bytes (2)

  • <
  • 1
  • 2
  • 3
  • 4
  • >

Keith Thompson

Simon Biber <ne**@ralmin.cc > writes:

Kenneth Brody wrote:
Thanks. (And thanks to everyone else who answered.) I had a feeling
that that would be the case, but the *printf() functions seem to be
"special", in that the compiler can do type-checking at compile time
(given a literal format specifier), and I was afraid that there might
be some other "special" things about it.

They aren't special, from a language point of view. A standard C
compiler is not required to do type-checking of the variable arguments
of printf functions. The fact that some compilers do this is an extra,
non-standardised feature.

The *printf() functions are somewhat special in that they're part of
the standard library, so the compiler is allowed to make assumptions
about what they do. For example, a call like

printf("%d", 1.5);

invokes undefined behavior. The compiler is allowed to issue a
diagnostic (which is really beside the point, since a compiler may
issue a diagnostic for any reason at any time), but it's also allowed
to generate code that, for example, aborts the program rather than
calling printf(). And for a correct printf() call like:

printf("%s\n", "Hello, world");

the compiler may replace the printf() call with

puts("Hello, world");

It wouldn't be allowed to do these things for a user-defined
my_printf() function with the same prototype, *unless* it's able to
determine at compilation time (or at link time) how the user-defined
function actually behaves. For functions in the standard library, the
compiler is allowed to make these assumptions without analyzing the
implementation of the function, because the behavior is guaranteed by
the standard.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.

Nov 15 '05 #21

Stan R.

Richard Tobin wrote:

In article <42**********@s pool9-west.superfeed. net>,
Stan R. <st*********@br emove.lz.hmrpri nt.com> wrote:
Going out on a limb here, but has anyone ever written (for practical
use) a function that /actually/ /took/ 127 args?!?!?! (I almost
cringe at the though of a function declaration taking up half a
page! :-P )

Even 31 seems big for an arg list!

Some graphical interfaces have used vararg/stdarg argument lists with
alternating name-value arguments, and these can quite reasonably be
fairly long, though more than 30 arguments would be unusual even for
this case.

Good point, but the arg lists in a case like you described doesn't need
to be so long.

a) Encapsolate the name-value pair to a struct or class, and pass
instances of the struct instead (cutting the arg list in half. Or...

b) Cut it down to one arg by using something of the sort of a linked
list, thus just passing the first pointing, and the function keeps going
until it hits the NULL (end.)

c) not having used c for some time (been using c++ for year now after
using c for a while), I honestly can't remebmer if there are classes,
but iff you, one could write a Map or Hash type class, or just use
<map.h> :-)

Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------
http://www.usenet.com

Nov 15 '05 #22

Keith Thompson

"Stan R." <st*********@br emove.lz.hmrpri nt.com> writes:

Richard Tobin wrote:
In article <42**********@s pool9-west.superfeed. net>,
Stan R. <st*********@br emove.lz.hmrpri nt.com> wrote:
Going out on a limb here, but has anyone ever written (for practical
use) a function that /actually/ /took/ 127 args?!?!?! (I almost
cringe at the though of a function declaration taking up half a
page! :-P )

Even 31 seems big for an arg list!
Some graphical interfaces have used vararg/stdarg argument lists with
alternating name-value arguments, and these can quite reasonably be
fairly long, though more than 30 arguments would be unusual even for
this case.

Good point, but the arg lists in a case like you described doesn't need
to be so long.

a) Encapsolate the name-value pair to a struct or class, and pass
instances of the struct instead (cutting the arg list in half. Or...

C has no classes.

Even with C99's compound literals, the call is going to be
considerably more verbose than with alternating name-value arguments.
For example, in C99

func(WIDTH, 40, HEIGHT, 50, LAST_ARG);

might become

func((arg_type) {WIDTH, 40},
(arg_type){HEIG HT, 50},
(arg_type){LAST _ARG, 0});

And that's ignoring the possibility of different types of arguments,
which would probably require unions and named designators. It gets
very ugly very quickly.

C90 has no compound literals, so you'd need separate code to
initialize the argument objects before passing them to the function.
b) Cut it down to one arg by using something of the sort of a linked
list, thus just passing the first pointing, and the function keeps going
until it hits the NULL (end.)
Again, you's have to construct the linked list separatey before
calling the function, and destroy it afterwards.
c) not having used c for some time (been using c++ for year now after
using c for a while), I honestly can't remebmer if there are classes,
but iff you, one could write a Map or Hash type class, or just use
<map.h> :-)

See above.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.

Nov 15 '05 #23

Richard Tobin

In article <42**********@s pool9-east.superfeed. net>,
Stan R. <st*********@br emove.lz.hmrpri nt.com> wrote:

a) Encapsolate the name-value pair to a struct or class, and pass
instances of the struct instead (cutting the arg list in half. Or...

b) Cut it down to one arg by using something of the sort of a linked
list, thus just passing the first pointing, and the function keeps going
until it hits the NULL (end.)

In one of the systems of this kind that I used, the original interface
was an array of name-value structs. This was verbose and tedious to
type, and the varargs version was added to make it more usable.

-- Richard

Nov 15 '05 #24

Christian Kandeler

Kenny McCormack wrote:

int foo(int a) { return a; }

void bar(void) { return foo(1,2,3); }

Works fine on 99.99% of all hardware

Although you'd first have to write a compiler which accepts this.
Christian

Nov 15 '05 #25

Kenny McCormack

In article <42************ ***********@new s.sunsite.dk>,
Christian Kandeler <ch************ ****@hob.de_inv alid> wrote:

Kenny McCormack wrote:
int foo(int a) { return a; }

void bar(void) { return foo(1,2,3); }

Works fine on 99.99% of all hardware

Although you'd first have to write a compiler which accepts this.

Christian

I'm sure compilers exist (from the early dawn era of prototypes)
that would, but today, you would just rearrange it to:

void bar(void) { return foo(1,2,3); }
int foo(int a) { return a; }

And ignore the warning about implicit declaration of foo().

Nov 15 '05 #26

pete

Kenny McCormack wrote:


In article <42************ ***********@new s.sunsite.dk>,
Christian Kandeler <ch************ ****@hob.de_inv alid> wrote:
Kenny McCormack wrote:
int foo(int a) { return a; }

void bar(void) { return foo(1,2,3); }

Works fine on 99.99% of all hardware


Works fine? Meaning that you don't know what it does
and you don't know what it's supposed to do?

What is bar supposed to do?
A function call to bar has no value and no side effects.

It's just simply undefined.

N869
6.5.2.2 Function calls
Constraints
[#2] If the expression that denotes the called function has
a type that includes a prototype, the number of arguments
shall agree with the number of parameters.

6.8.6.4 The return statement
Constraints
[#1] A return statement with an expression shall not appear
in a function whose return type is void.
Although you'd first have to write a compiler which accepts this.

--
pete

Nov 15 '05 #27

Kenny McCormack

In article <42***********@ mindspring.com> ,
pete <pf*****@mindsp ring.com> wrote:

Kenny McCormack wrote:

In article <42************ ***********@new s.sunsite.dk>,
Christian Kandeler <ch************ ****@hob.de_inv alid> wrote:
>Kenny McCormack wrote:
>
>> int foo(int a) { return a; }
>>
>> void bar(void) { return foo(1,2,3); }
>>
>> Works fine on 99.99% of all hardware

Works fine? Meaning that you don't know what it does
and you don't know what it's supposed to do?

OK, little boy. Change it to "int bar" if it makes you happy.

Or change it from "return foo" to "printf foo" (with suitable syntax to
make it compilable).

Nov 15 '05 #28

pete

Kenny McCormack wrote:


In article <42***********@ mindspring.com> ,
pete <pf*****@mindsp ring.com> wrote:
Kenny McCormack wrote:

In article <42************ ***********@new s.sunsite.dk>,
Christian Kandeler <ch************ ****@hob.de_inv alid> wrote:
>Kenny McCormack wrote:
>
>> int foo(int a) { return a; }
>>
>> void bar(void) { return foo(1,2,3); }
>>
>> Works fine on 99.99% of all hardware

Works fine? Meaning that you don't know what it does
and you don't know what it's supposed to do?

OK, little boy. Change it to "int bar" if it makes you happy.

Or change it from "return foo" to "printf foo"
(with suitable syntax to make it compilable).

The point,
is that you're not paying attention to what you're saying,
because you know better than to do that.

--
pete

Nov 15 '05 #29

Kenny McCormack

In article <42***********@ mindspring.com> ,
pete <pf*****@mindsp ring.com> wrote:

Kenny McCormack wrote:

In article <42***********@ mindspring.com> ,
pete <pf*****@mindsp ring.com> wrote:
>Kenny McCormack wrote:
>>
>> In article <42************ ***********@new s.sunsite.dk>,
>> Christian Kandeler <ch************ ****@hob.de_inv alid> wrote:
>> >Kenny McCormack wrote:
>> >
>> >> int foo(int a) { return a; }
>> >>
>> >> void bar(void) { return foo(1,2,3); }
>> >>
>> >> Works fine on 99.99% of all hardware
>
>Works fine? Meaning that you don't know what it does
>and you don't know what it's supposed to do?

OK, little boy. Change it to "int bar" if it makes you happy.

Or change it from "return foo" to "printf foo"
(with suitable syntax to make it compilable).

The point,
is that you're not paying attention to what you're saying,
because you know better than to do that.

I see what you mean, but I think there is a sense in which you ought to be
able to read text posted here for content and in context - rather than just
looking for any little thing to nit-pick.

Obviously, the point of the thread and the thing being discussed was the
calling of foo() with more parameters than it was declared with. I think it
was clear enough to anyone what the point was, unless, of course, the
reader is, as is all too common in this ng, just reading to look for
something to nitpick. The declaration and use of bar was clearly outside
of the main channel of the discussion.

Nov 15 '05 #30

  • <
  • 1
  • 2
  • 3
  • 4
  • >

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

Similar topics

11 5949

printf with run-time format strings

by: Grumble |last post by:

Hello, I have the following structure: struct foo { char *format; /* format string to be used with printf() */ int nparm;/* number of %d specifiers in the format string */ /* 0 <= nparm <= 4 */ };

C / C++

7 2553

Write a customized printf function in C

by: sunfiresg |last post by:

During an interview, I am asked to answer a question: Printf is a major formatted output function provided by the standard C library. Printf accepts a formatting string followed by a various number of arguments to replace formatting specifiers in the formatting string. You should implement the subset of the printf function compliant to the following specification.

C / C++

31 2625

Strange behaviour of printf. See the code below and please tell why it behaves in this way.

by: DeltaOne |last post by:

#include<stdio.h> typedef struct test{ int i; int j; }test; main(){ test var; var.i=10; var.j=20;

C / C++

9 2791

Printf("%d")

by: geek |last post by:

Hi all, Why does a printf("%d") statement prints this as output and when I do printf("%c") it doesn't print anything. -13361016 Any help would be appreciated. Thanks,

C / C++

5 1745

Multiple Arguements like in printf

by: bg_ie |last post by:

Hi, I'd like to write a function like printf, which takes a string as its first arguement, but then a variable number of arguements after this, based on the contents of the first arguement. How do I do this? Barry.

C / C++

18 2854

program having printf() function invocation without including <stdio.h>

by: sam_cit |last post by:

Hi Everyone, int main() { printf("not included stdio.h"); } Yes, i haven't included stdio.h and my compiler would generate a warning and would assume that it would return a int, my question is how does the linker manage to link the function invocation to the proper

C / C++

491

Re: Extend functionality of printf (Add colours)

by: =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?= |last post by:

On Nov 10, 6:26pm, Tomás Ó hÉilidhe <t...@lavabit.comwrote: You use the TOE_PLATFORM macro to choose your platform. 1 is Unix. 2 is Windows. Here's what I've got so far. Any comments are welcomed: #define SPECIAL_CHAR ('^') #include <stdarg.h /* For variable length argument lists */ #include <stdio.h /* vsprintf, printf */

C / C++

9 25631

How to override standard printf defined in gcc library

by: RahulJain83 |last post by:

Hi, I am Rahul. We have a complete software written out (with n other shared libraries maintained by various other teams). The shared libraries are loaded at run time by the main executable depending upon what feature user wants to run. All across our code, we are using printf and fprintf to print messages on the screen for the user. Now, we are adding a Graphical interface to our software and require that all such messages are displayed in...

C / C++

8969

What is ONU?

by: marktang |last post by:

ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...

General

8788

Changing the language in Windows 10

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,...

Windows Server

9335

Maximizing Business Potential: The Nexus of Website Design and Digital Marketing

by: jinu1996 |last post by:

In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...

Online Marketing

1 9263

The easy way to turn off automatic updates for Windows 10/11

by: Hystou |last post by:

Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...

Windows Server

9208

Discussion: How does Zigbee compare with other wireless protocols in smart home applications?

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...

General

6053

Couldn’t get equations in html when convert word .docx file to html file in C#.

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();...

C# / C Sharp

1 3279

transfer the data from one system to another through ip address

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

C# / C Sharp

2 2745

How to add payments to a PHP MySQL app.

by: muto222 |last post by:

How can i add a mobile payment intergratation into php mysql website.

PHP

3 2193

Comprehensive Guide to Website Development in Toronto: Expert Insights from BSMN Consultancy

by: bsmnconsultancy |last post by:

In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

General

printf() with too many args -- legal? | Bytes (2024)

References

Top Articles
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 5807

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.