Thursday, April 9, 2009

The first line of a source file contains the following line.The compiler warns about "struct x declared inside parameter list". What is the compiler worried about?

extern int f(struct x *);

For two structures to be compatible, they must not only have the same tag name but be defined in the same scope. A function prototype, however, introduces a new, nested scope for its parameters. Therefore, the structure tag x is defined in this narrow scope, which almost immediately disappears. No other struct x pointer in this translation unit can therefore be compatible with f's first parameter, so it will be impossible to call f correctly (at least, without drawing more warnings). The warning alluded to in the question is trying to tell you that you shouldn't mention struct tags for the first time in function prototypes.

(The warning message in the question is actually produced by gcc, and the message runs on for two more lines, explaining that the scope of the structure declared "is only this definition or declaration, which is probably not what you want.")

What is output of following recusive main function call ?

main()
{
static int s=5;
s--;
printf("%d",s);
(s>3)?main():0;
}

Output: 43

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: %%