[libc-commits] [PATCH] D84469: [libc] Adds implementation for memrchr.

Siva Chandra via Phabricator via libc-commits libc-commits at lists.llvm.org
Fri Jul 24 11:01:26 PDT 2020


sivachandra added inline comments.


================
Comment at: libc/src/string/memrchr.cpp:18
+  const unsigned char ch = c;
+  while (n--) {
+    if (str[n] == ch)
----------------
cgyurgyik wrote:
> sivachandra wrote:
> > For better readability, may be:
> > 
> > ```
> > for (; n != 0; --n) {
> >   ...
> > }
> > ```
> Are you looking for something along these lines:
> ```
> for (; n != 0; --n) {
>       if (str[n] == ch) return const_cast<unsigned char *>(str + n);
>   }
>   return str[0] == ch ? const_cast<unsigned char *>(str) : nullptr;
> ```
> Or, am I missing something simpler here?
Very close:

```
for (; n != 0; --n) {
  const unsigned char *s = str + n - 1;
  if (*s == ch)
    return const_cast<unsigned char *>(s);
}
return nullptr;
```

The post decrement you have currently makes it easy miss that `n - 1` offset.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D84469/new/

https://reviews.llvm.org/D84469





More information about the libc-commits mailing list