Cannot initialize integer [closed] - c++

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 4 years ago.
Improve this question
I have a method loading:
-(void)loading:(MKTileOverlayPath)path ... {
...
Within this method I am trying to calculate something
NSInteger *a = pow(2, path.z) - path.y - 1;
I get an error:
Initializing 'NSInteger *' (aka 'long *') with an expression of incompatible type 'double'
Why is that double? path.z and path.y are, as stated in the documentation MKTileOverlayPath, integer. And pow(2, path.z) cannot result in an float or double neither, when there are only integers... Why is that?

You have two errors:
The standard C pow() produces a double and it's parameters are also double - your integer arguments are implicitly cast for you. There is no version for integer types. The best solution is not to use casts to get an integer value, that introduces the possibility of errors doe to the nature of floating-point math, but to simply write your own integer power function. You can copy the one in this answer - just implement it using the integer type (int, long etc.) you require.
You have confused your variable type, object types are reference types and declared as pointers, e.g. NSString *; simple numeric types are value types and are not pointers, e.g. NSInteger.

Mathematically it won't result in a non-integer value, but that's not the contract for the pow() function. According to http://www.cplusplus.com/reference/cmath/pow/, the parameters are being implicitly cast to doubles and the return value of the function is always a double.

Related

Comparisons involving literals safe? [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 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.

Should I use an unsigned char instead of an int to store values that will never be greater than 255? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In a C++ program I am writing for fun there are frequently numeric values being used that will absolutely never be greater than 255, and I am therefore storing them as unsigned chars to save on memory used (as an unsigned char only uses a byte, as opposed to the 4 bytes of an int). Is this a good idea? Are there any downsides to doing this?
I appreciate tips and insight anyone can give.
It's a trade-off.
Given that you are using unsigned char to represent non-negative (presumably) values that don't exceed 255, you will save on memory usage for storing the particular values.
If your code does arithmetic operations on those unsigned char, then the values may be implicitly promoted to int, the operation done using ints, and then the result converted back. This is consistent with the fact that quite a few real-world machines do not have machine registers that work directly with char types, but do have registers and instructions that are optimised for a larger "native" integral type i.e. int. Such to-and-fro conversions can mean that code which does a sequence of operations on unsigned chars can have measurably lower speed than coding to use variables of type int. (Notionally, an implementation might "optimise out" such to-and-fro conversions, if analysis shows there is no change of observable result from a sequence of operations, but it is not required to)
Generally speaking, for representing numeric values, I would suggest not using unsigned char and to default to using int (or another suitable integral type if the range of values you need to represent goes beyond the range that an int is guaranteed able to represent). Get the code working first and, if you decide to optimise your code to save on memory, do testing/profiling on representative target systems to determine the extent of any performance impact of using unsigned char. If using C++11 or later, you might also consider using uint8_t (on implementations that support it) but bear in mind there may be similar trade-offs with that as well.
There isn't really any downside but you might not use lesser memory depending on the order of your member variable definitions because of padding bytes(this only applies to classes).

Typecasting in C++: why use (type) expression instead of type (expression) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
In python, type casting is done as:
float(a) if the variable a is, say an integer and needs to be converted to float.
Now consider the following C++ code:
int a=5;
int b=10;
cout<< (float) a/b<<endl;
cout<<static_cast<float> (a/b)<<endl;
cout<<static_cast<float> (a)/b;
which gives the output:
0.5
0
0.5
In the first type cast, a is type casted to float explicitly, and then b is type casted implicitly. The final answer is of the type float.
In the second and third type cast, depending on the position of the () either a is first explicitly converted to float, then b implicitly converted and then then the final value is 0.5 or a/b is first calculated as an int, and then type casted to float, making the final value 0.
There is no ambiguity while using static_cast<type>(expr)
My question being:
Wouldn't this be a lot clearer if the first line was written like:
cout<<float(a)/b<<endl;
Eliminating any ambiguity regarding in which order the type casting will be done?
C++ has no restrictions on doing just that, and yet it isn't common practice. Rather, cout<<(int)a/b<<endl; is the prevelant form, which seems to be more ambiguous.
Why is this the case?
Another way to frame this question would be: what advantage does the (type) expression offer over type (expression)?
The main advantage of (type)a over type(a) is that the first works for any type and the second doesn't. Try the following and you will elicit compiler errors;
unsigned long x = unsigned long(3.0);
unsigned long *y = unsigned long *(0);
Beyond that, your question is based on a completely false premise. Contrary to your description, there is no ambiguity in the meaning of any of the expressions you describe.
(float) a/b;
static_cast<float> (a/b);
static_cast<float> (a)/b;
because the second has different meaning from the other two. float)a/b and static_cast<float>(a)/b both convert a to float before performing the division. static_cast<float>(a/b) do the division and then converts the result to float.
Your real problem is that you don't understand that division a/b, when a and b are of type int, produces a result of type int.
I would also suggest not holding up Python as an exemplar of how C++ should handle such things. Python 2.x produced an integral-valued result on integral division too (albeit, with slightly different behaviour than in C++). Python 3.x introduced the so-called "true division". There was a lot of heated discussion in the Python community over that.
Another way to frame this question would be: what advantage does the
(type) expression offer over type (expression)?
Actually, they are almost the same...
(type) expression is a C-style cast
and
type (expression) also casts, but has limitations with respect to certain types(int*, const char* etc); Additionally, its also a constructor call for class types.

Assign octal/hex declared INT/UINT to another variable [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 7 years ago.
Improve this question
My WIN32 (C++) code has a UINT lets call it number.
The value of this UINT (or INT doesn't matter) start with a 0 and is recognized as an octal value. It's possible to use the standart operators and the value will keep the octal-system. The same is possible with hex (with foregoing 0x).
The problem is I have to use the Value of number in a buffer to calculate with it without changing the value of number. I can assign a value like 07777 to buffer on declaration line but if use an operation like buffer = number the value in buffer is recognized on decimal base.
Anybody has a solution for me?
There's no such thing in C as an "octal value". Integers are stored in binary.
For example, these three constants:
10
012
0xA
all have exactly the same type and value. They're just different notations -- and the difference exists only in your source code, not at run time. Assigning an octal constant to a variable doesn't make the variable octal.
For example, this:
int n = 012;
stores the value ten in n. You can print that value in any of several formats:
printf("%d\n", n);
printf("0%o\n", n);
printf("0x%x\n", n);
In all three cases, the stored value is converted to a human-readable sequence of characters, in decimal, octal, or hexadecimal.
Anybody has a solution for me?
No, because there is no actual problem.
(Credit goes to juanchopanza for mentioning this in a comment.)

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.