473,698 Members | 2,084 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
16 2807
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********@yah oo.com) (cb********@wor ldnet.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_item s < 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********@yah oo.com) (cb********@wor ldnet.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_ch ars" 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_ch ars" 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*****@bigfoo t.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_ch ars" 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*******@free net.de)
Nov 13 '05 #16
In <rt************ *************** @netnews.attbi. com> Rudolf <rt*****@bigfoo t.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_ch ars" 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
6474
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 answer here? If a is converted to unsigned, then b>a. But, if b is converted to signed,then a>b. What's the correct coversion (what is the compiler supposed to do?)
11
1587
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 loaded. Suddenly I notice a certain value generates a warning. Here's the low-down: The specific instance of the "-6" in this phrase generates a warning: const signed long tzerocal_A ={80000, 15000, -60000 }; //bad
43
2709
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 holds strings of any length. I guess what is happening here is that this array initially holds only '\0' and hence is of length 1. But sometimes, when I tried to write some functions and do some
3
2567
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 libs; use /NODEFAULTLIB:library Here is the compiler options: /Od /I "C:\DriverX4\Include" /I "..\ThreadLib" /AI "..\Utility\bin\Debug" /AI "..\Logging\bin\Debug" /AI "Debug" /D "WIN32" /D "_DEBUG" /D "_WINDLL"
6
35667
by: fctk | last post by:
hello, i'm trying to compile this small program: int main(void) { unsigned long int max; max = 4000000000;
8
2006
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 this: warning: semantics of ">>" change in ANSI C; use explicit cast The statement to which this applies is: xuc = ((uc & 0xF0 ) >4);
7
1775
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 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,...
39
2656
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 of the value range for values which you will never be using. I agreed with this, and started to always use 'unsigned' whenever negative values wouldn't make any sense. I did this for years. However, I slowly changed my mind: Doing this often...
13
2722
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
8672
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9021
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8892
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8860
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4361
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3038
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2323
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1998
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.