Thursday, April 9, 2009

What is the ANSI Standard definition of a null pointer constant?

Answer: "An integral constant expression with the value 0, or such an expression cast to type (void *)".

Are the parentheses in a return statement mandatory?

Answer: No. The formal syntax of a return statement is

return expression ;

But it's legal to put parentheses around any expression, of course, whether they're needed or not.

How can %f work for type double in printf and %lf is required in scanf?

Answer: In variable-length argument lists such as printf's, the old "default argument promotions" apply, and type float is implicitly converted to double. So printf always receives doubles, and defines %f to be the sequence that works whether you had passed a float or a double.


(Strictly speaking, %lf is *not* a valid printf format specifier, although most versions of printf quietly excepts it.)

scanf, on the other hand, always accepts pointers, and the types pointer-to-float and pointer-to-double are very different (especially when you're using them for storing values). No implicit promotions apply.

Why doesn't \% print a literal % with printf?

Answer: Backslash sequences are interpreted by the compiler (\n, \", \0, etc.), and \% is not one of the recognized backslash sequences. It's not clear what the compiler would do with a \% sequence -- it might delete it, or replace it with a single %, or perhaps pass it through as \ %. But it's printf's behavior we're trying to change, and printf's special character is %. So it's a %-sequence we should be looking for to print a literal %, and printf defines the one we want as %%.

How can you print a literal % with printf?

Answer: %%