1

I have narrowing conversion error in C++ arm from Android NDK.

Have a following code:

int16_t ax = li.A.x, ay = li.A.y;
int16_t bx = li.B.x, by = li.B.y;
Rect16 rcA = { ax - 8, ay - 8, ax + 8, ay + 8 };
Rect16 rcB = { bx - 8, by - 8, bx + 8, by + 8 };

And get this error, when try to compile:

error: narrowing conversion of '(((int)ay) + -0x00000000000000008)' from 'int' to 'int16_t' inside { }

Rect16 struct:

typedef struct tagRect16 {
    int16_t left, top, right, bottom;
} Rect16;
Mihail Krivushin
  • 480
  • 1
  • 5
  • 13

1 Answers1

1

Your problem stems from the fact that in the expression ay - 8 the compiler says you are calling int operator-(int, int). You need to tell the compiler that 8 is a short, using a method like in this question.

Community
  • 1
  • 1
Gideon Engelberth
  • 6,095
  • 1
  • 21
  • 22
  • Yeah, I try to define int16_t eight = 8; and use it, but have no success - compiler cast it to int. compiler cast both args to int. – Mihail Krivushin Dec 20 '10 at 14:04
  • In that case all I can suggest is casting the result explicitly, as in `(int16_t)(ay - 8)`. Basically, the error is saying "There's a conversion here, but it may lose data for some values, so you have to tell me if you want it." Sometimes (like here) the fix is to just cast the result, sometimes the fix is to change the arguments to make sure the function you actually meant is called. – Gideon Engelberth Dec 20 '10 at 14:49
  • It works! But - why? Explicit work and implicit not? Compiler suppose I know about conversion, and dont mean error there? – Mihail Krivushin Dec 20 '10 at 14:54
  • Why? Because the compiler vendor decided to do that. The standard simply says: "If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined." – Gene Bushuyev Dec 20 '10 at 16:07
  • @Deepwalker: Along with what Gene said, a cast is a way of telling the compiler "I know what I'm doing" and you are willing to take responsibility for the consequences. The cast says, "store this value in 16 bits, even though it may lose data (from the top 16 bits)." At that point, the compiler gets out of your way and does what you say you want. Fortunately, the compiler never says "I told you so" if you have to change it back. – Gideon Engelberth Dec 20 '10 at 17:20