1

why does this code below give the correct output

#include <iostream>
#include <string>
using namespace std;
int main()
{
int max=0;
string k ="hello";
if(k.length()>max){
    max = k.length();
}
    cout<<max;
}

but this code below doesn't?

#include <iostream>
#include <string>
using namespace std;
int main()
{
int max=-1;
string k ="hello";
if(k.length()>max){
    max = k.length();
}
    cout<<max;
}

alinsoar
  • 15,386
  • 4
  • 57
  • 74
Deus Ex
  • 117
  • 1
  • 8
  • there might be some issue with integer promotion – dvhh Jun 09 '20 at 06:19
  • Check in the documentation what type is returned by `k.length()` and then check what happens when comparing this type with `int` (the type of `max` – Alex Lop. Jun 09 '20 at 06:21
  • The value `-1` converted to `unsigned` yields something like positive 4 billion something. You are not comparing negative numbers! – pmg Jun 09 '20 at 06:28

2 Answers2

1

This may be due to type conversion. Your max may be conversion to unsigned because k.lenght is unsigned.

Anton Shwarts
  • 515
  • 2
  • 10
0

If you try to compare the max with k.length() by explicit conversion, it'll work.

The k.length() will return you unsigned long long, but the max was signed int. It might be the reason of the error. To solve it, let's do something like:

Look at the following:

#include <iostream>

using namespace std;

int main()
{
    int max = -1;
    string k ="hello";

    if(int(k.length()) > max) // use int()
        max = k.length();

    cout << max;
}

In other words, both the sides of comparison should be the same for a successful comparison.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34