Interview Questions

I have a function ...

C Interview Questions and Answers


(Continued from previous question...)

I have a function ...

Q: I have a function
extern int f(int *);
which accepts a pointer to an int. How can I pass a constant by reference? A call like
f(&5);
doesn't seem to work.

A: In C99, you can use a ``compound literal'':
f((int[]){5});
Prior to C99, you couldn't do this directly; you had to declare a temporary variable, and then pass its address to the function:
int five = 5;
f(&five);
In C, a function that accepts a pointer to a value (rather than simply accepting the value itself) probably intends to modify the pointed-to value, so it may be a bad idea to pass pointers to constants.ndeed, if f is in fact declared as accepting an int *, a diagnostic is required if you attempt to pass it a pointer to a const int. (f could be declared as accepting a const int * if it promises not to modify the pointed-to value.)

(Continued on next question...)

Other Interview Questions