Comparisons involving literals safe? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Consider the code:
#define LITERAL 1.0
int main()
{
double x = LITERAL;
if (x == LITERAL) return 1;
else return 0;
}
Is this guaranteed to return 1 for any numerical double value we set LITERAL (not just 1.0 but any other double literal)?
EDIT: Why was the question closed because of "missing details"? It is a well defined C/C++ question and got a very good answer. There are no more details required, it is a general question about how these languages work.

First, you have to assume an implementation that's (attempting to be) conforming to Annex F, since otherwise all bets are off; without Annex F (IEEE floating point) C allows all floating point results to be arbitrarily bogus.
Then, according to the language spec, depending on your C implementation's definition of FLT_EVAL_METHOD, yes or no.
If the value is 0 or 1, then yes. The literal is interpreted as double, and the double object stores that value faithfully, and the equality operator yields 1 (true), reflecting that.
If the value is 2, then only if the literal is the eact decimal representation of a representable double or is expressed with sufficient precision that it differs from one only past the precision of long double. Otherwise (for example if it's something like 0.1), since the literal is interpreted with excess precision in long double format the initialization/assignment to a double object truncates the precision to the nominal double precision. Then the equality comparison is guaranteed to result in 0 (false). You can see this in action on Compiler Explorer (note: remove the volatile and you can see it optimized to return a constant 0).
To make matters more complicated, GCC does this wrong by default unless you use -std=c.. or -fexcess-precision=standard, and always does it wrong in C++ mode, and clang/LLVM always do it wrong. So on a target with excess precision (32-bit x86 or m68k, the only real-world-relevant targets with FLT_EVAL_METHOD not 0 or 1) horrible things happen. For a peek into how bad they get, see GCC issue 93806 and (recursively) all of the "See Also" related issues.
So for practical purposes, yes, for everything but 32-bit x86 and m68k, and in a correct C implementation no (but maybe yes, because your compiler is probably broken) for them.

Related

logic behind assign binary literals to an int [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Found that logic on a code and don't get the reason behind that; why use it instead of assign normal int?
(its a character controller in a 3D environment)
// assumes we're not blocked
int blocked = 0x00;
if ( its_a_floor )
blocked |= 0x01;
if ( its_a_wall )
blocked |= 0x02;
0x00 is a "normal int". We are used to base 10 representations, but other than having 10 fingers in total, base 10 is not special. When you use an integer literal in code you can choose between decimal, octal, hexadecimal and binary representation (see here). Don't confuse the value with its representation. 0b01 is the same integers as 1. There is literally no difference in the value.
As a fun fact and to illustrate the above, consider that 0 is actually not a decimal literal. It is an octal literal. It doesn't really matter, because 0 has the same representation in any base.
As the code is using bit-wise operators it would be most convenient to use a binary literals. For example you can see easily that 0b0101 | 0b10101 equals 0b1111 and that 0b0101 & 0b1010 equals 0b0000. This isn't that obvious when using base 10 representations.
However, the code you posted does not use binary literals, but rather hexadecimal literals. This might be due to the fact that binary literals are only standard C++ since C++14, or because programmers used to bit wise operators are so used to hexadecmials, that they still use them rather than the binary.

Function pow() int C++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a problem when I try to multiply integer 3 pow(67, 1). It return 200 instead 201. Here is my code in C:
int x = 3;
x = x * pow(67, 1);
printf("%d\n", x);
-> 200
Can anyone explain for me. Thanks!
Tentative explanation: the pow function, being performed in double precision, does not "understand" that a power of 1 means "return the exact number" and returns 66.9999. (Lots of 9's but not exactly 67). The multiplication by 3 gives something like 200.99997. Finally since the result is assigned to an int, this is rounded down (truncated) to 200.
pow(67,1) should not compile as C++03, but as Tony observes in a comment, 1C++11's §26.8/11 makes it valid again in C++11. Visual C++ 12.0 rejects the code as C++, evidently playing by C++03 rules. However, the g++ compiler version 4.8.2 accepts the code. With Visual C++ one gets a diagnostic about ambiguous call, since there are many overloads.
In C or in C++11 the arguments are converted to double and pow performs the exponentiation. Although these numbers can be represented exactly as double, the exponentiation operation is not guaranteed to produce an exact integer. E.g. it might be performed as an = en*ln(a).
The result can therefore be slightly more or less than exact 67.
The multiplication expression converts integer 3 to double, exactly, and the multiplication is performed as double. If the pow result is less than 67 then you get a result like 200.9999999..., if it's exact than you get 201.0, and if it's slightly more then you get something like 201.0000001....
Finally the assignment back to x converts that back down to nearest int value, which in the first case is 200, and in the second and third case is 201.
2I can only conclude that the claimed result 200 must (most probably) be incorrect; that it's incorrectly reported.
1)C++11 §26.8/11: “Moreover, there shall be additional overloads sufficient to ensure: 1. If any argument corresponding to a double parameter has type long double, then all arguments corresponding to double parameters are effectively cast to long double. 2. Otherwise, if any argument corresponding to a double parameter has type double or an integer type, then all arguments corresponding to double parameters are effectively cast to double. 3. Otherwise, all arguments corresponding to double parameters are effectively cast to float.”.
2)See commentary for the deleted text.

How to check if a number is zero? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
if(number == 0) {
//do something
}
Since zero evaluates to false in C++, if a number is zero it will be false in if condition.
how can I check if it is really a number zero?
There is a misconception, here: the if statement is not about the 0 constant or the value of number, but about the returned value of operator==.
The point is not if number or 0 are themselves equivalent to "false", but if == returns true or not. And it returns true if the operands have the same value.
As far integral types promotions work, the above assertion works for whatever pair of integral types.
If number is something else, then all relates to the convertibility towards a common type between number and int (since 0 is a n int) and to the "precision" the number value may have, or in the way operator== is implemented between the two types.
You can experience some trouble if number is a floating point. If this is your case, just compare with a reasonable small around of zero. Have a look at this article http://floating-point-gui.de/errors/comparison/ I'm sure you can better understand the problem.
Trivial example:
#define epsilon 0.0001;
if( fabs(number) < epsilon ){
....
}
choosing the correct epsilon could be tricky, depending on the application.

How to ensure the function return consistent floating point values in C/C++? [duplicate]

This question already has answers here:
How deterministic is floating point inaccuracy?
(10 answers)
Closed 9 years ago.
How to enure the function return consistent floating point values in C/C++?
I mean: if a and b are of floating point type, if I wrote a polynomial function (which takes floating point argument and returns floating point results), lets call it polyfun(), do the compiler can ensure that:
if a==b, then polyfun(a)==polyfun(b), which means the order of maths ops/rounding up are consistent at runtime?
Reproducible results are not guaranteed by the language standards. Generally, a C implementation is permitted to evaluate a floating-point expression with greater precision than the nominal type. It may do so in unpredictable ways, such as inlining a function call in one place and not another or inlining a function call in two places but, in one place, narrowing the result to the nominal type to save it on the stack before later retrieving it to compare it to another value.
Some additional information is in this question, and there are likely other duplicates as well.
Methods of dealing with this vary by language and by implementation (particularly the compiler), so you might get additional information if you specify what C or C++ implementation you are using, including the details of the target system, and if you search for related questions.
Instead of polyfun(a)==polyfun(b) try ABS(polyfun(a) - polyfun(b)) < 1e-6, or 1e-12 or whatever you find suitably appropriate for "nearness"... (Yeah, cumulative float point errors will still kill you.)

check NaN number [duplicate]

This question already has answers here:
Checking if a double (or float) is NaN in C++
(21 answers)
Closed 1 year ago.
Is it possible to check if a number is NaN or not?
Yes, by use of the fact that a NaN is not equal to any other number, including itself.
That makes sense when you think about what NaN means, the fact that you've created a value that isn't really within your power to represent with "normal" floating point values.
So, if you create two numbers where you don't know what they are, you can hardly consider them equal. They may be but, given the rather large possibility of numbers that it may be (infinite in fact), the chances that two are the same number are vanishingly small :-)
You can either look for a function (macro actually) like isnan (in math.h for C and cmath for C++) or just use the property that a NaN value is not equal to itself with something like:
if (myFloat != myFloat) { ... }
If, for some bizarre reason, your C implementation has no isnan (it should, since the standard mandates it), you can code your own, something like:
int isnan_float (float f) { return (f != f); }
Under Linux/gcc, there's isnan(double), conforming to BSD4.3.
C99 provides fpclassify(x) and isnan(x).
(But C++ standards/compilers don't necessarily include C99 functionality.)
There ought to be some way with std::numeric_limit<>... Checking...
Doh. I should have known... This question has been answered before...
Checking if a double (or float) is NaN in C++
Using NaN in C++?
http://bytes.com/topic/c/answers/588254-how-check-double-inf-nan
you are looking for null, but that is only useful for pointers. a number can't be null itself, it either has a known value that you put in there or random data from whatever was there in memory before.