I’ve been going over and refactoring some code. I ended up changing a function from:
void setPerspective(float nearP = 0.1f, float farP = 1000.0f);
to
void setPerspective(float near = 0.1f, float far = 1000.0f);
and started getting a lot of strange 'missing ;' and 'missing )' errors.
It seems that near and far are #defined in windef.h. Fair enough; I’ll avoid using them.
But then I noticed in another header file:
void setPerspective(float fov, float aspect, float near, float far);
Yet I get no trouble. Both of these header files have the same #includes…
Any idea why I’m getting issues in one, but not another? It doesn’t seem to be the default parameters. Is it some arbitrary ordering of the #includes that might be causing issues with one header file and not another?
The tokens
nearandfarare probably defined to be null in an empty#definelike thisso the pre-processor will replace them with null – they disappear prior to the compiler processing the source.
The first function declaration includes the default assignment to the parameters
The compiler correctly interprets nearP and farP as the parameter name and
floatas the type. When you changenearPtonearandfarPtofarthe pre-processor replaces them with null and you have an assignment to thefloattype… and the compiler throws a fit… this is what the compiler sees:In the second header file the parameters in the function prototype don’t have default assignment, and the compiler sees the parameters are float and doesn’t see
nearandfarbecause they are null… so instead of thisthe compiler sees this
which is a perfectly legal function prototype (you don’t have to give the parameters names).