tags:

views:

471

answers:

3

Recently in an interview I was asked about what the signature of printf is. I really couldn't get a right answer. Would someone be able to shed some light on this?

+17  A: 
int printf ( const char * format, ... );

They were probably asking this to see if you were familiar with the optional parameter syntax "...". This allows you to pass an indeterminate list of variables that will fill in the format string.

For example, the same method can be used to print things like this:

printf("This is a string: %s", myString);
printf("This is a string: %s and an int: %d", myString, myInt);
Andy White
Or they might have been wondering if the interviewee knew printf() returns an int.
Mitch Haile
To be honest, I didn't know it returned an int until just now
Andy White
I hope they were after the variatic syntax. If they wanted to know about the return type, the question was a terrible one. You don't want to work there.
Steve Rowe
Yeah I agree with that. I hate when you get an interviewer that just tries to trick you with some obscure thing that nobody ever uses
Andy White
@Andy White: then how have you been checking for error conditions? :)
ysth
Whoops... I guess I haven't been. I'll stick with Console.WriteLine or System.out.println - those return void :)
Andy White
That's the C89 version: in C99, you need a restrict in there, too: int printf(const char * restrict format, ...);
Jonathan Leffler
Ha ha, I've never heard of "restrict." I think I'm content with not knowing what that is.
Andy White
@Andy: in most cases, you can get away with that; in some cases, the compiler might produce sub-optimal code, though
Christoph
when asking about scanf, i suspect return value questions become important
Johannes Schaub - litb
@Christoph: Get away with what?
Andy White
@Andy: get away with not knowing what `restrict` is
Christoph
@Andy: see eg http://www.cellperformance.com/mike_acton/2006/05/demystifying_the_restrict_keyw.html (first hit on google for `gcc restrict`)
Christoph
If I ever write C code again, I'll check it out, but for now, ignorance is bliss.
Andy White
+5  A: 

printf is a variadic function with the following signature:

int printf(const char *format, ...);

this means that it has one required string parameter, followed by 0 or more parameters (which can be of various types). Finally, it returns an int which represents how many characters are in the result.

The number and type of the optional parameters is determined by the contents of the format string.

Evan Teran
+2  A: 

Method signature, for some additional context.

Bryan