why does C++ forbid the declaration of a parameter with no type?

274 Views Asked by At

I would like to have the following method as a generic method for any array,

int arrayLength(`anyType` array[])
{
    return sizeof(array) / sizeof(array[0]);
}

However it appears C++ doesn't allow any ambiguity of types at all,

why is this, and how should I go about getting around it?

3

There are 3 best solutions below

0
On BEST ANSWER

Because types have to be pushed onto the stack and then popped back off, and the sizeof one type is not equal to the sizeof another type.

If the size of types being passed on the stack between functions is not fixed or known in advance, how can the compiler compile a function?

The solutions to this problem -- as others have noted -- is templates and macros, both of which dynamically generate code -- which is then, in turn, compiled -- at compile-time, appearing to "solve" the problem, but really only obviating or distracting you from it by offloading the work onto the compiler.

0
On

In Visual C++ there's a __countof() construct that does the same. It's implemented as a template for C++ compiling and as a macro for C. The C++ version errors out if used on a pointer (as opposed to a true array), the C version does not.

0
On

I think what you're really asking is "Why does C++ insist on static typing?"

The answer: because it's easier to write a compiler that generates small, fast programs if the language uses static typing. And that's the purpose of C++: creating small, fast programs whose complexity would be relatively unmanageable if written in C.

When I say "small", I'm including the size of any required runtime libraries.