Interview Questions

What does it mean for a function parameter to be const?

C Interview Questions and Answers


(Continued from previous question...)

What does it mean for a function parameter to be const?

Q:What does it mean for a function parameter to be const? What do the two const's in

int f(const * const p)
mean?

A: In int f(const * const p)

the first of the two const's is perfectly appropriate and quite useful; many functions declare parameters which are pointers to const data, and doing so documents (and tends to enforce) the function's promise that it won't modify the pointed-to data in the caller. The second const, on the other hand, is almost useless; all it says is that the function won't alter its own copy of the pointer, even though it wouldn't cause the caller or the function any problems if it did, nor is this anything the caller should care about in any case. The situation is the same as if a function declared an ordinary (non-pointer) parameter as const:

int f2(const int x)

This says that nowhere in the body of f2() will the function assign a different value to x. (Compilers should try to enforce this promise, too.) But assigning a different value to x wouldn't affect the value that the caller had passed (because C always uses call-by-value), so it's an unimportant guarantee, and in fact a pretty useless one, because what does the function gain by promising (to itself, since it's the only one that could care) whether it will or won't be modifying in the passed-in copy of the value?

(Continued on next question...)

Other Interview Questions