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
2009-03-11 04:49:42
Or they might have been wondering if the interviewee knew printf() returns an int.
Mitch Haile
2009-03-11 04:52:42
To be honest, I didn't know it returned an int until just now
Andy White
2009-03-11 04:54:31
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
2009-03-11 05:48:17
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
2009-03-11 05:50:49
@Andy White: then how have you been checking for error conditions? :)
ysth
2009-03-11 06:13:47
Whoops... I guess I haven't been. I'll stick with Console.WriteLine or System.out.println - those return void :)
Andy White
2009-03-11 06:16:38
That's the C89 version: in C99, you need a restrict in there, too: int printf(const char * restrict format, ...);
Jonathan Leffler
2009-03-11 06:36:37
Ha ha, I've never heard of "restrict." I think I'm content with not knowing what that is.
Andy White
2009-03-11 06:41:54
@Andy: in most cases, you can get away with that; in some cases, the compiler might produce sub-optimal code, though
Christoph
2009-03-11 10:04:47
when asking about scanf, i suspect return value questions become important
Johannes Schaub - litb
2009-03-11 15:01:30
@Christoph: Get away with what?
Andy White
2009-03-11 15:37:30
@Andy: get away with not knowing what `restrict` is
Christoph
2009-03-11 17:39:46
@Andy: see eg http://www.cellperformance.com/mike_acton/2006/05/demystifying_the_restrict_keyw.html (first hit on google for `gcc restrict`)
Christoph
2009-03-11 17:45:48
If I ever write C code again, I'll check it out, but for now, ignorance is bliss.
Andy White
2009-03-11 18:20:18
+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
2009-03-11 04:50:03