lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 6/26/16, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
>> A project I'm contributing to gets compiled with -Wfloat-conversion
>> and -Wbad-function-cast (and I can't change this). The compiler is
>> gcc.
>> [...]
>> On the other hand, if I write that line as:
>>
>>   off_t a = (off_t)lua_tonumber(L, -1);
>>
>> I inhibit that warning but get a different one because of the
>> -Wbad-function-cast:
>>
>>     " warning: cast from function call of type 'lua_Number {aka double}'
>>       to non-matching type 'long long int' [-Wbad-function-cast] "
>>
>> [...]
>>
>> I know I can solve this problem by doing instead:
>>
>>     lua_Number num = lua_tonumber(L, -1);
>>     off_t a = (off_t) num;
>
> Maybe a little off-topic, but why would a compiler accept
> '(off_t)num' but warn about '(off_t)lua_tonumber(L, -1)', when
> both 'num' and the result of 'lua_tonumber' are double?
>
> -- Roberto

I searched the 'net for the rationale for -Wbad-function-cast (which
makes the compiler warn about casts from function calls only, not from
variables) but couldn't quite find such.

I think I found a clue in the way the manual described this warning in
the past.[1] It used to say:

    "Warn whenever a function call is cast to a non-matching type.
     For example, warn if `int malloc()` is cast to `anything *`."

So it seems that the purpose was to flag the use of functions that
have no prototypes (which would lead to an `int malloc()`), especially
as this could lead to shady casts sometimes. In this case there's only
sense in flagging function calls: '(off_t)lua_tonumber(L, -1)', but
not '(off_t)num'. But why should the compiler warn only when the
programmer does explicit cast? I don't know.

And there are other '-W' warnings that handle the case of missing
prototypes, so I don't see why -Wbad-function-cast is needed. Maybe
it's for the case when you have old source code that sees missing
prototypes as legitimate.

By coincidence, Sean Conner just today wrote[2] in this mailing list
about malloc() missing the declaration.

[1] https://gcc.gnu.org/ml/gcc-patches/2015-01/msg00758.html
[2] http://lua-users.org/lists/lua-l/2016-06/msg00380.html