Search code examples
c++stringalgorithmstring-length

string::length() returning garbage value


I am trying to use string::length() inside a function I wrote, named match(), but I'm getting garbage values.

Why does the marked line is outputting garbage values?

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

void match(string st1,string st2)
{
    for(int i=0;i<st1.length();i++)
    {
        cout<<"Why this value is garbage "<<(i-st1.length()-1)<<"\t";
        // this expression gives wrong values ^^^^^^^^^^^^^^^
    }
}

int main()
{
    string st1,st2;
    cout<<"Enter the required string\n";
    cin>>st1>>st2;
    match(st1,st2);
    return 0;
}

Solution

  • imagine a string "foo":

    i-st1.length()-1 means:

    when i is 0:

    0 - 3 = -3
      - 1 = -4
    

    but st1.length() is a size_t, which is unsigned, so all terms in the expression are promoted to unsigned values.

    (unsigned)0 - (unsigned)3 = 0xfffffffffffffffd
                          - 1 = 0xfffffffffffffffc
    
                              = 18446744073709551612