Conversion to "USHORT" from 'int' may alter its value

1.3k views Asked by At

I'm having some troubles in adapting a piece of code for an embedded platform.

eMBFuncReadCoils( UCHAR * pucFrame, USHORT * usLen )

The line above is the prototype of the function I'm having troubles with.

The problem is about the *usLen pointer with the following instruction:

*usLen += 1;

USHORT is defined as follows:

typedef unsigned short USHORT; 

Compiler says:

error: conversion to 'USHORT' from 'int' may alter its value [-Werror=conversion]
         *usLen += 1;

I cannot figure out what might be the problem.

And why it's bringing up an error because of int ?

I also thought to rewrite the assignment like this:

*usLen = *usLen + 1;

But nonetheless noting changes.

Thanks

3

There are 3 answers

1
Serge Ballesta On BEST ANSWER

I would say the compiler option ([-Werror=conversion]) is to blame here. The expression *usLen += 1; is syntactic sugar for that one:

*usLen = *usLen + 1;

So you add an unsigned short and an int. The unsigned short value is promoted to an int (assumint int can represent all unsigned short values which is true for all common 32 and 64 bits architectures), and you end up assigning an int to an unsigned short which can truncate values but is perfectly defined by C standard. It is normally a warning on common options, but here the error says that the compiler was specifically instructed to raise an error.

You can either relax the compiler options, or if you have good reasons for them, just use an explicit conversion which should be allowed:

*usLen += (unsigned short) 1;

or

*usLen = (unsigned short) (*usLen + 1);
0
Patrice F On

Perhaps 1 is considered as an int, and (*uslen + 1) the result of the operation is an int too, then the affectation in a ushort may lead to loss of information. For info : ushort are coded on 2 bytes form 0 to 65535 int are coded on 2 or 4 (depending on the compiler and processor) from -32 768 to 32 767 or form -2 147 483 648 to 2 147 483 647 Perhaps you souhld try something like *usLen = *usLen + (USHORT) 1; or *usLen = (USHORT)(*usLen + (USHORT) 1); and test of the max value before doing the addition Hope that could help

0
Dulguun On

You have to convert 1 to USHORT:

  1. *usLen += (unsigned short) 1;
  2. *usLen += (USHORT) 1;