truncation warning

M

Magix

Hi,
I have following code.

char buffer[161];

void string_addchar(char *sourc, char ch)
{
int length;

length=strlen(sourc);
sourc[length]=ch;
sourc[length+1]=0;
}

string_addchar(buffer,0xA8); // 2 warnings on this line

I will get following warning on above string_addchar statement:
warning C4305: 'argument' : truncation from 'const int' to 'char'
warning C4309: 'argument' : truncation of constant value

How should I fix that ?
 
J

Jens.Toerring

Magix said:
Hi,
I have following code.
char buffer[161];
void string_addchar(char *sourc, char ch)
{
int length;
length=strlen(sourc);
sourc[length]=ch;
sourc[length+1]=0;
}

string_addchar(buffer,0xA8); // 2 warnings on this line
I will get following warning on above string_addchar statement:
warning C4305: 'argument' : truncation from 'const int' to 'char'
warning C4309: 'argument' : truncation of constant value

That's related to your passing 0xA8 as a character. The warnings
tell you that you're passing an int (and that's what 0xA( is) to
a function that expects a char. Moreover, 0xA8 can be too large to
be stored in a char, at least when on your system char is signed,
in which case the maximum value for a char might be (and often is)
as small as 0x7F. And in that case the value you pass to the func-
tion gets truncated to something that still fits into a char (which
could be something you might not want).

The warnings should go away once you pass the function a value not
larger than CHAR_MAX (defined in <limits.h>). That can be achieved
by explicitely casting 0xA8 to char (thereby telling the compiler
you're convinced that you know what you're doing). The alternative
is to change your function to accept an unsigned char as its second
argument.
Regards, Jens
 
R

Ravi Uday

Magix said:
Hi,
I have following code.

char buffer[161];

void string_addchar(char *sourc, char ch)
{
int length;

length=strlen(sourc);
sourc[length]=ch;
sourc[length+1]=0;
}

string_addchar(buffer,0xA8); // 2 warnings on this line

I will get following warning on above string_addchar statement:
warning C4305: 'argument' : truncation from 'const int' to 'char'
warning C4309: 'argument' : truncation of constant value

How should I fix that ?

Do you think 0xA8 will fit in 'char' ?? Try converting from char to
'unsigned char'

When i compiled in conforming mode I only got this -

*warning: overflow in implicit constant conversion*

- Ravi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top