Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of gcc's -Wbad-function-cast?

As advised by an answer here, I turned on -Wbad-function-cast to see if my code had any bad behavior gcc could catch, and it turned up this example:

unsigned long n;
// ...
int crossover = (int)pow(n, .14);

(it's not critical here that crossover is an int; it could be unsigned long and the message would be the same).

This seems like a pretty ordinary and useful example of a cast. Why is this problematic? Otherwise, is there a reason to keep this warning turned on?

I generally like to set a lot of warnings, but I can't wrap my mind around the use case for this one. The code I'm working on is heavily numerical and there are lots of times that things are cast from one type to another as required to meet the varying needs of the algorithms involved.

like image 317
Charles Avatar asked Oct 10 '13 21:10

Charles


People also ask

Why Gulf countries are important?

The GCC nations account for nearly 65 per cent of India's impressive annual remittances of more than $80 billion in the last three years. They host a bulk of Indian migrants — nearly nine million in all. These countries account also for almost 15 per cent of India's global trade.

What is meant by GCC countries?

Meaning of the GCC in English abbreviation for Gulf Cooperation Council: a group of six countries in the Persian Gulf: Bahrain, Kuwait, Qatar, Oman, Saudi Arabia, and the United Arab Emirates.

What are Gulf countries and why they are called so?

Countries are gulf countries because they lie on the border of the Persian Gulf. Gulf countries are: Bahrain. Kuwait. Iraq.

What are the 7 Gulf countries?

The Gulf Cooperation Council countries – Bahrain, Kuwait, Oman, Qatar, Saudi Arabia and the United Arab Emirates – are important markets for EU agricultural exports.


1 Answers

You'd better to take this warning seriously.

If you want to get integer from floating-point result of pow, it is rounding operation, which must be done with one of standard rounding functions like round. Doing this with integer cast may yield in surprises: you generally loose the fractional part and for instance 2.76 may end up as 2 with integer truncation, just as 2.12 would end up as 2. Even if you want this behavior, you'd better to specify it explicitly with floor function. This will increase readability and supportability of your code.

like image 105
Konstantin Vladimirov Avatar answered Oct 25 '22 04:10

Konstantin Vladimirov