3

I am new to c++. I need help fixing this error:

Item.cpp: In member function ‘char* ict::Item::sku() const’:
Item.cpp:65:36: warning: comparison between signed and unsigned integer 
expressions [-Wsign-compare]

This is the part of the code that is giving the error:

//in header file
char m_sku[MAX_SKU_LEN + 1];

//in cpp file
char* Item::sku() const
{
    int length = strlen(m_sku);
    char *arr = new char[length]();
    for (int i = 0; i <= strlen(m_sku); i++) {
        arr[i] = m_sku[i];
    }
    return arr;
}
John C
  • 517
  • 2
  • 6
  • 16
  • 3
    change `int I` to `std::size_t` The latter is unsigned and is the type returned by strlen() which can never be negative. Comparing unsigned and signed ints can lead to some very hard to find problems hence the warning. The warning is because both the ints are converted to unsigned and if one is negative it becomes a large positive number so you can get some really odd results. Possible duplicate of http://stackoverflow.com/questions/5416414/signed-unsigned-comparisons – doug Apr 09 '17 at 05:41

2 Answers2

3

The most straightforward way to fix this is to make i an unsigned variable instead of a signed one. You can use size_t to match the return type of strlen:

size_t length = strlen(m_sku);
char *arr = new char[length]();
for (size_t i = 0; i <= length; i++) {
    arr[i] = m_sku[i];
}

But be careful since this same replacement doesn't work with loops that count down towards 0.

// oops! This is an infinite loop:
for (size_t i = length-1; i >=0; i--) {
    arr[i] = m_sku[i];
}
hugomg
  • 68,213
  • 24
  • 160
  • 246
1

Write a static cast (int)strlen(m_sku) or vice versa std::size_t i = 0. So that compared items will be the same.

Timur Kukharskiy
  • 303
  • 3
  • 16