Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: Comparison between signed and unsigned integer expression

Tags:

c++

class

I am running hhe following code on codepad.org and I am getting this error. "In member function 'double Xchange::getprice(std::string)': Line 87: warning: comparison between signed and unsigned integer expressions"

This is my code:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Xchange
{
public:
    Xchange();//does nothing (?)

    double getprice(string symbol);

private:
    vector <Stock> stocks;
};

double Xchange::getprice(string symbol)
{
    for(int i=0; i < stocks.size(); i++) {
        if(stocks[i].getsymbol()==symbol) {
            return stocks[i].getprice();
        }
    }

    return -1; //means not found
}
like image 786
victor vaughn Avatar asked Dec 20 '22 22:12

victor vaughn


1 Answers

Here:

for(int i=0; i < stocks.size(); i++)

i is a signed integer, stocks.size() is unsigned. You can use std::size_t, or, if you want to be more precise, use the vector<Stock>::size_type.

for(vector<Stock>::size_type i=0; i < stocks.size(); i++) { .... }

The problem this warning is trying to prevent is that a negative signed to unsigned conversion yields a large number and is most likely not what you want. Besides that, the numerical range of a signed integer is no the same as that of an unsigned one of the same size.

See C++ types for more information.

Note that this is easier in C++11:

for(const auto& stock : stocks)
{
    if(stock.getsymbol()==symbol) //added getsymbol "()"
    {
        return stock.getprice();
    }
}
like image 121
juanchopanza Avatar answered Feb 16 '23 01:02

juanchopanza