Search code examples
c++pointerstypesreferencearguments

How it can be legal to pass a variable with a data type to a function?


I am currently examining DLL to a very specific measurement device which is called "force plate" and produced by Advanced Mechanical Technology, Inc. It measures ground reaction forces generated by a human standing or moving across them. This DLL is written in Visual C++ (as programmers reference says) and provided by manufacturer of force plate.

So, there is a function which is called fmDLLTransferFloatData. This is how it is declared in DLL's header file:

int DLLExport fmDLLTransferFloatData(float *&data);

It returns an int and requires a reference to a pointer to float data. So far so good. And here comes the strange part of this function, the way it must be used in a code according to programmers reference:

float *ptr;
int ret;

//getting the Data
ret = fmDLLTransferFloatData((float *&)ptr);

Take a look at the argument syntaxis: ((float *&)ptr). And it works. Can someone explain what does this syntaxis actually means?

So, as I've already said, this function works fine, I am actually will be very glad if someone explain this weird syntaxis to me.


Solution

  • The expression (T)E where T is a type and E an expression is a C-style cast or explicit type conversion. It converts the expression E to the type T. Of all of C++'s cast expressions, it is the one that permits the largest set of conversions.

    However, It does absolutely nothing with the context you are showing. If ptr is a variable of type float* then the expressions ptr and (float *&)ptr are 100% exactly equivalent.

    So you can just write ptr instead.

    In fact, using the C-style cast (float *&) is a bad practice since it can easily cause serious problems to go unnoticed. The cast will almost always succeed, regardless of what type ptr is, but if it isn't actually float*, then it will almost surely cause undefined behavior. However a compiler won't diagnose this as an error or warning, because the cast essentially tells the compiler to just do it without complaining, no matter how dangerous it may be.

    There is almost never a need to use C-style casts in C++. C++ has static_cast, const_cast and reinterpret_cast instead, each of which permits only a smaller subset of conversions and are therefore more specific and safer to use. In most cases static_cast is sufficient to replace C-style casts and in other cases extra care must be taken.