-1

Cannot understand how the following code works.

String::npos 

I cannot figure out how does it works. Please anyone help me out with that.

Sami
  • 9
  • 4
  • 1
    That code doesn't compile. Please see [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – ruakh Mar 11 '21 at 01:39
  • 1
    Clearly there must be more to this code than just what you have shown. Some earlier code must be calling a `find...()` method on a `std::string` and saving the result to the `found` variable, which will be set to `npos` if the searched-for data is not found in the string. – Remy Lebeau Mar 11 '21 at 01:39
  • *"Is there any return value"* -- since there is no `return` statement, I'll go with "no". I suppose technically, there are values returned by the `<<` operators (one value enabling the operator chain and the other unused) but that is probably not what you meant to ask about. – JaMiT Mar 11 '21 at 02:10

1 Answers1

-2

std::string::npos returns an integer value (-1) which is used to determine whether or not a value is inside a string.

In the example provided here: https://en.cppreference.com/w/cpp/string/basic_string/npos you see the author uses .find('a') to find 'a' char inside the string "test". Because the char 'a' does not hold a position in the string (npos literally translates to no position) it returns -1.

nyk
  • 1
  • 2
  • 5
    It doesn't "return" anything, it's a constant. Furthermore it must be unsigned (and therefore cannot have the value `-1`). – M.M Mar 11 '21 at 01:54