3

The following code prints 1010

#include <iostream>
#include <range/v3/algorithm/starts_with.hpp>

int main () {
    using namespace std::literals;
    std::cout << ranges::starts_with("hello world"s, "hello"s)
              << ranges::starts_with("hello world"s, "hello")
              << ranges::starts_with("hello world",  "hello"s)
              << ranges::starts_with("hello world",  "hello") << std::endl; // prints 1010

}

Why is that?

I've also noticed that if the two stings are the same, then also the last case returns 1:

    std::cout << ranges::starts_with("hello world"s, "hello world"s)
              << ranges::starts_with("hello world"s, "hello world")
              << ranges::starts_with("hello world",  "hello world"s)
              << ranges::starts_with("hello world",  "hello world") << std::endl; // prints 1011

I know that a std::string, such as "bla"s, is a range, and that a char[N] is a range too, given a constant N. So I don't see why

Enlico
  • 23,259
  • 6
  • 48
  • 102

1 Answers1

4

A string literal like "hello" is a const char[N] array, where N includes space for the null terminator, eg char[6] = {'h','e','l','l','o','\0'}.

A string literal like "hello"s is a std::string object, which does not include the null terminator in its size().

So, you end up with:

starts_with("hello world"s, "hello"s) = 1
// {'h','e','l','l','o',' ','w','o','r','l','d'}
// DOES begin with
// {'h','e','l','l','o'}

starts_with("hello world"s, "hello") = 0
// {'h','e','l','l','o',' ','w','o','r','l','d'}
// DOES NOT begin with
// {'h','e','l','l','o','\0'}

starts_with("hello world",  "hello"s) = 1
// {'h','e','l','l','o',' ','w','o','r','l','d','\0'}
// DOES begin with
// {'h','e','l','l','o'}

starts_with("hello world",  "hello") = 0
// {'h','e','l','l','o',' ','w','o','r','l','d','\0'}
// DOES NOT begin with
// {'h','e','l','l','o','\0'}

starts_with("hello world"s, "hello world"s) = 1
// {'h','e','l','l','o',' ','w','o','r','l','d'}
// DOES begin with
// {'h','e','l','l','o',' ','w','o','r','l','d'}

starts_with("hello world"s, "hello world") = 0
// {'h','e','l','l','o',' ','w','o','r','l','d'}
// DOES NOT begin with
// {'h','e','l','l','o',' ','w','o','r','l','d','\0'}

starts_with("hello world",  "hello world"s) = 1
// {'h','e','l','l','o',' ','w','o','r','l','d','\0'}
// DOES begin with
// {'h','e','l','l','o',' ','w','o','r','l','d'}

starts_with("hello world",  "hello world") = 1
// {'h','e','l','l','o',' ','w','o','r','l','d','\0'}
// DOES begin with
// {'h','e','l','l','o',' ','w','o','r','l','d','\0'}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770