-3

The error is when I compare the value an int to the strnlen of a char with a set string length. what I am doing is searching the string for a certain # and tracking if it is found or not.

for (value = 0; value < strlen(stringValue) && !searchFound; value++)
{

    if (stringValue[value] == searchDigit)
    {
        numberTimesSearchFound = numberTimesSearchFound + 1;

        //ends loops once it is found
        searchFound = true;

    } //end of string value if else loop}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294

1 Answers1

1

strlen returns size_t which is an unsigned type. You compare this to value which is a signed type. In C, values have to be of the same type to be compared, and the rule here is that value will be converted to size_t before the comparison.

In your code this is no problem (except for the case I mention later about INT_MAX), there are other situations where signed-unsigned comparisons do contain bugs. See here for example .

Because of this possibility, some compilers warn about all signed-unsigned comparisons, so that you can manually check your code for bugs.

To get rid of this warning I'd suggest changing value to have type size_t. If you go on to use value after the end of this code snippet then make sure that you weren't relying on any more signed-unsigned comparisons afterwards!

Ideally, scope it to the loop:

for ( size_t value = 0; ......

NB. If the string is longer than INT_MAX then your original code causes undefined behaviour when value is incremented beyond that; making value be size_t also fixes that problem.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365