News for hackers. Stuff that matters.
Re:In C++, is empty() faster than comparing the size with zero? by avianes on Friday October 29, 2021 @05:11AM (#29036707)
> I can forcefully bound the return value of count_nodes() to be no more than 1000. If I change the code to return a standard size_t type, like so…

  size_t count_nodes(const node* p) {
      size_t size = 0;
      while (p) {
          p = p->next;
          size++;
          if(size == 1000)
              return 1000; 
      }
      return size;
  }
> Sadly, GCC is now unable to optimize away the call. Maybe compilers are not yet all powerful beings?

Interestingly, this version is optimized by GCC and Clang:

  size_t count_nodes(const node* p) {
      size_t size = 0;
      while (p && (size < 1000)) {
          p = p->next;
          size++;
      }
      return size;
  }
https://godbolt.org/z/YKWbWb5zr

There are no comments on this comment yet.