473,398 Members | 2,188 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

warning - comparing a signed value to an unsinged value

What do you think is the best way to handle a compiler warning about
comparing an unsigned value to a signed value? Cast to silence it?
Disable that warning altogether? Or just live with it?

On one hand, the warning *could* be useful. Most of the time I get it in
cases where I know the comparison is safe, but it's not hard to imagine
that this won't always be the case. This makes disabling it undesirable.
Casting is a workable solution, but I worry that changes in the code
later could introduce errors that go undetected due to the cast. And I
think we all hate not having a "clean" compile (if only because having a
bunch of warnings that you expected makes it more difficult to spot the
ones you didn't expect).

What is your opinion?

Thanks.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Nov 13 '05 #1
16 2781
Kevin Goodsell wrote:
What do you think is the best way to handle a compiler warning about
comparing an unsigned value to a signed value? Cast to silence it?
Disable that warning altogether? Or just live with it?


You could always fix the code so that you aren't comparing a signed to
an unsigned.

Nov 13 '05 #2

"Kevin Goodsell" <us*********************@neverbox.com> wrote in message
news:mI*****************@newsread3.news.pas.earthl ink.net...
What do you think is the best way to handle a compiler warning about
comparing an unsigned value to a signed value?

[snip]

If you are using gcc then ;
gcc -W -Wall foo.c

--
=====================================
Alex Vinokur
mailto:al****@connect.to
http://mathforum.org/library/view/10978.html
news://news.gmane.org/gmane.comp.lang.c++.perfometer
=====================================

Nov 13 '05 #3
Kevin Goodsell wrote:

What do you think is the best way to handle a compiler warning about
comparing an unsigned value to a signed value? Cast to silence it?
Disable that warning altogether? Or just live with it?


IME, this usually occurs when you have a function which checks an int
value against some range, typically derived via sizeof (size_t, which is
unsigned). My suggestion, in this case, is to fix your functions so that
you use size_t for ranges and indices.

/david

--
Andre, a simple peasant, had only one thing on his mind as he crept
along the East wall: 'Andre, creep... Andre, creep... Andre, creep.'
-- unknown
Nov 13 '05 #4
T.M. Sommers wrote:
Kevin Goodsell wrote:
What do you think is the best way to handle a compiler warning about
comparing an unsigned value to a signed value? Cast to silence it?
Disable that warning altogether? Or just live with it?

You could always fix the code so that you aren't comparing a signed to
an unsigned.


That's not always possible without introducing new variables.

int SomeFunc(int *dest); /* returns error code, writes value to *dest */

int i;
if (SUCCESS == SomeFunc(&i))
{
if (i < sizeof(some_type))
{
/* ... */
}
}

I can't very well get an unsigned type from SomeFunc, nor can I cause
sizeof() to result in a signed type. The only way to make the comparison
deal with like types would be to add a new variable that logically
shouldn't exist. This is hardly any better than casting in the comparison.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Nov 13 '05 #5
Kevin Goodsell wrote:

What do you think is the best way to handle a compiler warning
about comparing an unsigned value to a signed value? Cast to
silence it? Disable that warning altogether? Or just live with it?

On one hand, the warning *could* be useful. Most of the time I get
it in cases where I know the comparison is safe, but it's not hard
to imagine that this won't always be the case. This makes
disabling it undesirable. Casting is a workable solution, but I
worry that changes in the code later could introduce errors that
go undetected due to the cast. And I think we all hate not having
a "clean" compile (if only because having a bunch of warnings that
you expected makes it more difficult to spot the ones you didn't
expect).

What is your opinion?


Spend a little time thinking. Assume we are talking about signed
and unsigned ints. Now, if the unsigned is larger than INT_MAX,
it is obviously larger than the int. If the int is negative, it
is obviously smaller than the unsigned. Having eliminated these
cases you can safely cast the int into unsigned, and then
compare. In fact, all you need to eliminate is the negative case.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 13 '05 #6
In <mI*****************@newsread3.news.pas.earthlink. net> Kevin Goodsell <us*********************@neverbox.com> writes:
What do you think is the best way to handle a compiler warning about
comparing an unsigned value to a signed value? Cast to silence it?
Disable that warning altogether? Or just live with it?


I prefer not to enable this warning. It never revealed a real bug in my
code and I'd never use a cast for the sole reason of silencing a warning.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #7
Kevin Goodsell wrote:
Why is everyone answering by
suggesting there's something wrong with the code?


The warning suggests that a better choice of types may be available.
I understand that that isn't the case.

--
pete
Nov 13 '05 #8
On Tue, 21 Oct 2003 06:40:26 +0000, Kevin Goodsell wrote:
Changing the type is not an option. As I told pete, 'SomeFunc' is
actually sscanf() with a %n format specifier.

The value is non-negative, but the interface requires an int. This is
beyond my control. If you want to file a defect report suggesting that
the %n format specifier for the *scanf functions should expect a size_t
instead of an int, be my guest. While you're at it, I believe there are
a few other standard library functions that use ints where size_t would
probably be more appropriate.

Maybe I should have been more clear in my post. I intended for you to
assume the types were dissimilar for some good reason and could not be
easily changed to similar types.

Yes, in your defect report be sure to include a note stating that Dennis
Ritchie (or whoever defined it) is an idiot for defining *scanf() the
way he did.


I feel I owe you an apology Kevin! It really was stupid of me to
attempt to answer your question by considering the different possibilites.
I should have realized right away that you are an expert. After all,
novices and inexperienced programmers hardly ever post anything in
comp.lang.c, and even if they did, I should have been able to recognize
your expertise by clairvoyantly reading your aura. I promise it will
never happen again. Please forgive me.

-Sheldon
Nov 13 '05 #9
Sheldon Simms wrote:


I feel I owe you an apology Kevin! It really was stupid of me to
attempt to answer your question by considering the different possibilites.
I should have realized right away that you are an expert. After all,
novices and inexperienced programmers hardly ever post anything in
comp.lang.c, and even if they did, I should have been able to recognize
your expertise by clairvoyantly reading your aura. I promise it will
never happen again. Please forgive me.


Sorry, I was feeling a bit frustrated with the replies I was getting. I
probably should have been more clear in my first message, and I
definitely should not have been as harsh in my replies as I was. I've
actually spent quite a bit of time here (though not lately), and getting
the "newbie treatment" irritated me, but it's probably my own fault for
not being clear enough. Again, I apologize.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Nov 13 '05 #10
Kevin Goodsell wrote:
.... snip ...
It just so happens that in the specific case that prompted the question,
I was comparing the result of a strlen() call to an int that was used as
the destination variable for a sscanf %n format specifier. If you can
suggest a way to persuade sscanf to use size_t instead of int for %n, or
a way to persuade strlen() to return int, then I suppose your answer
would be useful.

I asked a pretty simple question. Why is everyone answering by
suggesting there's something wrong with the code? Let me clarify: I have
two variables that need to be compared. Assume the types are dictated
by something beyond my control. One is a signed type and one is an
unsigned type. I know the comparison is safe because the signed variable
is non-negative. But the compiler warns about it. I was seeking opinions
on how to handle this. Changing the types is not an option.


IIRC you did not originally specify that the integer was known to
be positive. In this case you can obviously cast it to unsigned
without worries, and be done with it. The usage deserves a
comment, just in case someone somewhere passes in a negative value
in future. For example, the scanf might fail, and thus never set
the integer value, which thus needs initializing or other
avoidance.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 13 '05 #11
Kevin Goodsell wrote:
CBFalconer wrote:
No, one should understand the data one is working with, and
program accordingly.


And I do understand the data. But the problem persists.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
/* in the real program, buffer will be filled at run-time */
char buffer[] = " 0324 ";
long value;
int converted_items, scanned_chars = 0;

converted_items = sscanf(buffer, "%li %n", &value, &scanned_chars);

/* check if conversion failed: */
if (converted_items < 1 ||
(scanned_chars != 0 && scanned_chars < strlen(buffer)) )
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}

Unless I'm missing something, this code is perfectly fine. It should
convert the value from buffer to a long, allowing octal and hex
representations, and fail if the format is incorrect in any way. But the
comparison 'scanned_chars < strlen(buffer)' still causes a warning. The
question I am posing is, what do you consider the best way to handle a
situation like this?


I think the code is redundant. If sscanf ever scans past a '\0'
you have major problems with your library, so the strlen call is
pointless. I would write:

if (1 == sscanf(buffer, "%li%n", &value, &scanned_chars)) {
return EXIT_SUCCESS;
}
else {
return EXIT_FAILURE;
}

Note that I removed the space after %li. If you want to ensure a
terminating space you can also test:

if (' ' == buffer[scanned_chars]) ....

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 13 '05 #12
CBFalconer wrote:

I think the code is redundant. If sscanf ever scans past a '\0'
you have major problems with your library, so the strlen call is
pointless. I would write:

if (1 == sscanf(buffer, "%li%n", &value, &scanned_chars)) {
return EXIT_SUCCESS;
}
else {
return EXIT_FAILURE;
}

Note that I removed the space after %li. If you want to ensure a
terminating space you can also test:

if (' ' == buffer[scanned_chars]) ....


I believe you have misunderstood the intent of the code. The strlen()
call was to ensure that *all* characters were scanned (in other words,
that the buffer contained a valid integer and nothing else, except
possibly trailing or leading white space).

I'd like to go into more detail, but I have to run. It this is unclear,
I'll clarify later.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Nov 13 '05 #13
if (1 == sscanf(buffer, "%li%n", &value, &scanned_chars)) {
return EXIT_SUCCESS;
}
else {
return EXIT_FAILURE;
}

My question is off-topic from the original question, I'm curious if I'm
not understanding what sscanf returns. My documentation for the scanf
family says that the return value is "the number of input items
assigned." If that's the case, then the above code will return failure
if the sscanf gets a value for both "value" and "scanned_chars" since in
that case sscanf will return 2 and not 1.

Am I missing something?
Nov 13 '05 #14
Rudolf wrote:
if (1 == sscanf(buffer, "%li%n", &value, &scanned_chars)) {
return EXIT_SUCCESS;
}
else {
return EXIT_FAILURE;
}

My question is off-topic from the original question, I'm curious if I'm
not understanding what sscanf returns. My documentation for the scanf
family says that the return value is "the number of input items
assigned." If that's the case, then the above code will return failure
if the sscanf gets a value for both "value" and "scanned_chars" since in
that case sscanf will return 2 and not 1.

Am I missing something?


You're missing that %n is an exception: it's not counted as one of the
"input items assigned".

Jeremy.
Nov 13 '05 #15
Rudolf <rt*****@bigfoot.com> wrote:
if (1 == sscanf(buffer, "%li%n", &value, &scanned_chars)) {
return EXIT_SUCCESS;
}
else {
return EXIT_FAILURE;
}

My question is off-topic from the original question, I'm curious if I'm
not understanding what sscanf returns. My documentation for the scanf
family says that the return value is "the number of input items
assigned." If that's the case, then the above code will return failure
if the sscanf gets a value for both "value" and "scanned_chars" since in
that case sscanf will return 2 and not 1.

Am I missing something?


Yup. C99 7.19.6.2#12:

[...]
Execution of a %n directive does not increment the assignment count
returned at the completion of execution of the fscanf function.
[...]

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #16
In <rt***************************@netnews.attbi.com > Rudolf <rt*****@bigfoot.com> writes:

if (1 == sscanf(buffer, "%li%n", &value, &scanned_chars)) {
return EXIT_SUCCESS;
}
else {
return EXIT_FAILURE;
}

My question is off-topic from the original question, I'm curious if I'm
not understanding what sscanf returns. My documentation for the scanf
family says that the return value is "the number of input items
assigned." If that's the case, then the above code will return failure
if the sscanf gets a value for both "value" and "scanned_chars" since in
that case sscanf will return 2 and not 1.

Am I missing something?


Either your documentation is incredibly poor, or you didn't read it
carefully enough. What does it say about %n ?

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
by: MiniDisc_2k2 | last post by:
Okay, here's a question about the standard. What does it say about unsigned/signed mismatches in a comparison statement: char a = 3; unsigned char b = 255; if (a<b) Now what's the real...
11
by: Ross | last post by:
I'm compiling some code over and over with no problems. The only differences between the versions is slightly different constants that are specific to various embedded devices that are getting...
43
by: Anitha | last post by:
Hi I observed something while coding the other day: if I declare a character array as char s, and try to use it as any other character array..it works perfectly fine most of the times. It...
3
by: Bill Burris | last post by:
How do I find what is causing this warning from the Linker? If I use /NODEFAULTLIB I get hundreds of undefined symbols. LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other...
6
by: fctk | last post by:
hello, i'm trying to compile this small program: int main(void) { unsigned long int max; max = 4000000000;
8
by: Charles Sullivan | last post by:
I have a program written in C under Linux (gcc) which a user has ported to run under AT&T SysV R4. He sent me a copy of his makelog which displays a large number of compiler warnings similar to...
7
by: Nevil Lesdog | last post by:
What do you think is the best way to handle a compiler warning about comparing an unsinged value to a singed value? Cast to silence it? Disable that warning altogether? Or just live with it? On...
39
by: Juha Nieminen | last post by:
I was once taught that if some integral value can never have negative values, it's a good style to use an 'unsigned' type for that: It's informative, self-documenting, and you are not wasting half...
13
by: Andreas Eibach | last post by:
Hi, let's say I have this: #include <string.h> #define BLAH "foo" Later on, I do this:
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.