Is there anything wrong (potential undefined behavior) with the following code, were a float value gets assigned to a long int ?
struct timespec t;
t.tv_nsec = (some float value < 1) * 1E9
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The conversion would be done at compile time. You might get a warning from the compiler, but there’s nothing actually ‘wrong’ with the code, for all it is very aconventional to initialize an integer with a floating point constant.
Nanoseconds into
tv_nsec; interesting, but there shouldn’t be any major issues. A double in practice has enough precision that you won’t run into much trouble, though you might occasionally get a different value from what you expected because the fraction is truncated down when you didn’t expect it. It might be worth checking that; it depends how crucial it would be to you.I did a quick program to see whether there might be a problem. Bear in mind that this is run time calculation and not compile time calculation, but the results might be similar for you:
It prints out values where the fractional value does not match the integer value. A small section of some voluminous output is:
While it is by no means every value that has problems, I record (with
wc -l) 17,075,957 out of 1,000,000,000 values (or about 1.7% of the values) with a discrepancy. That was with GCC 4.1.2 on Mac OS X 10.7.4 (as supplied by Apple). I got the same result with GCC 4.7.0. It took about 30 seconds to generate the data.One of my favourite quotes from ‘The Elements of Programming Style’ by Kernighan and Plauger is:
This demonstrates the issue quite well.
Note that a trivial change reduces the error rate to 0:
Maybe you should use a macro:
You can use a smaller additive constant; 0.1 also reduced the error rate to 0.