stclib / STC

A modern, user friendly, generic, type-safe and fast C99 container library: String, Vector, Sorted and Unordered Map and Set, Deque, Forward List, Smart Pointers, Bitset and Random numbers.
MIT License
1.35k stars 73 forks source link

c_NPOS is not -1, differs from `std::string::npos` #103

Open liigo opened 1 month ago

liigo commented 1 month ago

in C++, the std::string::npos is -1, so someone may write:

string s = "test";
int i = s.find('e');
if (i >= 0) // same as `i != std::string::npos`
    cout << "found it at " << i << "\n";

but STC's c_NPOS is defined as INTPTR_MAX which is not -1. if you check i >= 0, then the code is error-prone.

tylov commented 1 month ago

I will consider changing to -1 because of some other reason, but it is more complicated: In c++, npos is of type size_t which is unsigned the largest number possible, but switching type or relying on the value of npos is not good. There are some functions, e.g. cstr_subview(s, pos, len), where you can pass in c_POS for len, and it will return to the end of the view (it stops at which comes first). I think this is also how it is working for some functions in c++.