473,581 Members | 2,786 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

negative number evaluating greater than string.size()

Hi, below is example code which demonstrates a problem I have encountered.
When passing a number to a function I compare it with a string's size and
then take certain actions, unfortunately during the testing of it I
discovered that negative numbers were being treated as if they were > 0. I
compiled the following on mingw compiler/dev c++/windows xp.

If I replace string.size() for a ordinary number it behaves as expected? I
notice string.size() returns size type and not an int but how do I deal with
that?

Thanks in advance for any help

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;

void something(int);

int main()
{
something(-1);
system("PAUSE") ;
return 0;
}

void something(int number) {
string str = "sdfjksdflksdjf kjsklfjsklfj";
if(number < str.size()) { cout << " hello" << endl; }
else { cout << " eek" << endl; }
}
Jul 22 '05 #1
25 2962
Jason wrote:
Hi, below is example code which demonstrates a problem I have encountered.
When passing a number to a function I compare it with a string's size and
then take certain actions, unfortunately during the testing of it I
discovered that negative numbers were being treated as if they were > 0. I
compiled the following on mingw compiler/dev c++/windows xp.

If I replace string.size() for a ordinary number it behaves as expected? I
notice string.size() returns size type and not an int but how do I deal with
that?

Thanks in advance for any help


GCC sez:

signed_probs.cp p: In function `void something(int)' :
signed_probs.cp p:17: warning: comparison between signed and unsigned
integer expressions

Changing line 17 to :

if(number < static_cast<int >(str.size()) ) { cout << " hello" << endl; }

solves the problem.
Jul 22 '05 #2

"Jason" <ja***********@ btinternet.com> wrote in message
news:c1******** **@titan.btinte rnet.com...
Hi, below is example code which demonstrates a problem I have encountered.
When passing a number to a function I compare it with a string's size and
then take certain actions, unfortunately during the testing of it I
discovered that negative numbers were being treated as if they were > 0. I compiled the following on mingw compiler/dev c++/windows xp.

If I replace string.size() for a ordinary number it behaves as expected? I notice string.size() returns size type and not an int but how do I deal with that?


Suggest you read the recent thread 'time to get rid of unsigned?', started
on 17/02/04.

john
Jul 22 '05 #3

"Gianni Mariani" <gi*******@mari ani.ws> wrote in message
news:c1******** @dispatch.conce ntric.net...
Jason wrote:
Hi, below is example code which demonstrates a problem I have encountered. When passing a number to a function I compare it with a string's size and then take certain actions, unfortunately during the testing of it I
discovered that negative numbers were being treated as if they were > 0. I compiled the following on mingw compiler/dev c++/windows xp.

If I replace string.size() for a ordinary number it behaves as expected? I notice string.size() returns size type and not an int but how do I deal with that?

Thanks in advance for any help


GCC sez:

signed_probs.cp p: In function `void something(int)' :
signed_probs.cp p:17: warning: comparison between signed and unsigned
integer expressions

Changing line 17 to :

if(number < static_cast<int >(str.size()) ) { cout << " hello" << endl; }

solves the problem.


Of course this is what the OP should do, but notice that the solution
effectively rules out strings where size() > INT_MAX. So why design for such
strings in the first place? Why not have size() return an int?

john

Jul 22 '05 #4
John Harrison wrote:
"Gianni Mariani" <gi*******@mari ani.ws> wrote in message
news:c1******** @dispatch.conce ntric.net...

signed_probs.c pp: In function `void something(int)' :
signed_probs. cpp:17: warning: comparison between signed and unsigned
integer expressions

Changing line 17 to :

if(number < static_cast<int >(str.size()) ) { cout << " hello" << endl; }

solves the problem.

Of course this is what the OP should do, but notice that the solution
effectively rules out strings where size() > INT_MAX. So why design for such
strings in the first place? Why not have size() return an int?


Because its more flexible to have a type where someone can
hold a string thats over 2Gb in size. I remember something
like this being used as a justification for making size_t
unsigned some 15 years back, either in GCC documentation or
the "Standard C library", in relation to malloc().

Naturally someone will tell you that you should be coding
everything that deals with sizes and lengths with size_t.
Jul 22 '05 #5

"lilburne" <li******@godzi lla.net> wrote in message
news:c1******** *****@ID-179504.news.uni-berlin.de...
John Harrison wrote:
"Gianni Mariani" <gi*******@mari ani.ws> wrote in message
news:c1******** @dispatch.conce ntric.net...

signed_probs.c pp: In function `void something(int)' :
signed_probs. cpp:17: warning: comparison between signed and unsigned
integer expressions

Changing line 17 to :

if(number < static_cast<int >(str.size()) ) { cout << " hello" << endl; }
solves the problem.
Of course this is what the OP should do, but notice that the solution
effectively rules out strings where size() > INT_MAX. So why design for such strings in the first place? Why not have size() return an int?


Because its more flexible to have a type where someone can
hold a string thats over 2Gb in size. I remember something
like this being used as a justification for making size_t
unsigned some 15 years back, either in GCC documentation or
the "Standard C library", in relation to malloc().


Interestingly the following code

int main()
{
std::string s;
std::cout << std::hex << s.max_size() << '\n';
}

when compiled with gcc 3.3.1 prints

3ffffffc

I don't think its a serious limitation to restrict yourself to strings which
occupy less than half of the available memory.

Naturally someone will tell you that you should be coding
everything that deals with sizes and lengths with size_t.


But what happens when you need to subtract one size from another? What type
should be used to hold the type of that operation? I don't think there is a
good answer.

john
Jul 22 '05 #6
> What type should be used to hold the type of that operation?

I meant

What type should be used to hold the result of that operation?
Jul 22 '05 #7
lilburne wrote:
Of course this is what the OP should do, but notice that the solution
effectively rules out strings where size() > INT_MAX. So why design
for such strings in the first place? Why not have size() return an
int?


Because its more flexible to have a type where someone can
hold a string thats over 2Gb in size.


I think it's not. You'd run into troubles if you need to calculate
offsets between two characters in your string. That offset might be
negative. Now you can't represent all possible offests anymore, no
matter whether you make the type for that offset signed or unsigned.
And further, if you mix signed and unsigned in your calculations, you
have to be very careful.

Jul 22 '05 #8
"John Harrison" <jo************ *@hotmail.com> wrote in news:c13cvl$1ds kq6$1
@ID-196037.news.uni-berlin.de:
What type should be used to hold the type of that operation?


I meant

What type should be used to hold the result of that operation?


size_t, assuming the programmer has done the sane thing and checked that
they are actually subtracting the smaller from the larger.
Jul 22 '05 #9
John Harrison wrote:
...
Changing line 17 to :

if(number < static_cast<int >(str.size()) ) { cout << " hello" << endl; }

solves the problem.


Of course this is what the OP should do, but notice that the solution
effectively rules out strings where size() > INT_MAX. So why design for such
strings in the first place? Why not have size() return an int?
...


In my opinion, using a signed type to store an unsigned quantity is a
low-level design error. For this reason, in many practical applications
signed types in C/C++ are much less useful than unsigned types. And
'size()' must return an unsigned value.

As for correcting the OP's code, I would suggest doing it differently

if (number < 0 || (std::string::s ize_type) number < str.size())
{ cout << " hello" << endl; }

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #10

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

Similar topics

3
3159
by: Tripp Knightly | last post by:
I have a lookup table from which I want to categorize various bands of customer net income. Some of the income is positive, some is negative. The bands vary in size (ie, <500, -200 to 0, 100 to 1000). When I have a lookup table w/ the "threshold" amounts of income, I'm not able to get dlookup to work, and I'm pretty sure it's getting...
11
2375
by: John | last post by:
Hi, I encountered a strange problem while debugging C code for a Windows-based application in LabWindows CVI V5.5, which led me to write the test code below. I tried this code with a different compiler and got the same erroneous result on two different PCs (with OS Win98 & Win98SE), so it appears to be a problem with ANSI C. I thought that...
23
5262
by: Davey | last post by:
How do I display an integer in binary format in C? e.g. 4 displayed as "100"
11
11918
by: tlyczko | last post by:
Hello Rob B posted this wonderful code in another thread, http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/c84d8538025980dd/6ead9d5e61be85f0#6ead9d5e61be85f0 I could not figure out how to reply to the thread per se using Google Groups and so please forgive me for cutting and pasting (I emailed him but he may not...
7
14086
by: andreas.lydersen | last post by:
Hi! While communicating with a monitoring unit, I get some hex values representing degrees celcius from its probes. The values can be something like '19' or '7d'. To convert it to int, I do the following: --------------------------- Python 2.4.2 (#1, Sep 28 2005, 10:25:47) on linux2 Type "help", "copyright", "credits" or "license" for...
11
3718
by: drtimhill | last post by:
I'm just starting out on Python, and am stumped by what appears an oddity in the way negative indices are handled. For example, to get the last character in a string, I can enter "x". To get the 2nd and 3rd to last, I can enter x etc. This is fine. Logically, I should be able to enter x to get the last and next to last characters. However,...
39
3981
by: Frederick Gotham | last post by:
I have a general idea about how negative number systems work, but I'd appreciate some clarification if anyone would be willing to help me. Let's assume we're working with an 8-Bit signed integer, and that it contains no padding. Firstly, I realise that the MSB is known as the sign-bit, and that it indicates whether the number is positive...
3
3002
by: hello2008 | last post by:
Hi, I donot have much knowledge of R.Exp. In my web page I am required to validate numeric textboxes allowing signed/unsigned integer/float numbers and then compare between them. I need the textboxes to accept values only between -10 to +10. Please help? Below is my code <html> <head> <title> Display Requirements </title>
6
18702
by: shashi shekhar singh | last post by:
Respected Sir, I am facing problem when i try to deploy my website on iis 7.0 on test page. i have to display some .mht files on iframe in gridview and error looks like below, Server Error in '/' Application. -------------------------------------------------------------------------------- Index was out of range. Must be non-negative and...
0
7882
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...
0
7808
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8157
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7914
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...
0
6564
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5683
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3809
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...
1
2309
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
0
1145
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...

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.