0

I want to loop over (unsigned) integers from 0 to 100. For that I have 2 options - use size_t, or auto:

#include <typeinfo>
#include <iostream>
#ifndef use_auto
#include <cstddef>
#endif

int main(){
#ifdef use_auto
#ifdef suffix
  constexpr auto num = 1;
#else
  constexpr auto num = 1ul;
#endif
  for (auto i = 0; i < num; i++){
    std::cout << "auto\n";
  }
#else 
  constexpr size_t num = 1;
  for (size_t i = 0; i < num; i++){
    std::cout << "explicit type\n";
  }
#endif
  std::cout << typeid(num).name() << '\n';
  return 0;
}
$ g++ bla.cpp && ./a.out | c++filt -t
explicit type
unsigned long
$ g++ bla.cpp -Duse_auto -Dsuffix && ./a.out | c++filt -t
auto
int
$ g++ bla.cpp -Duse_auto && ./a.out | c++filt -t
auto
unsigned long

Now, the branch defined under "use_auto" + "suffix" could be considered the best, as it:

  1. uses auto
  2. gets the correct type due to using integer literal

My question is more of a "best practice". For me, size_t seems clearer than auto num = 1ul, but I do like using auto as much as possible, for readablity and maintainanability.

Is there a concrete guideline on what's best to use here, or is this opinion based?

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • 2
    Why `size_t` instead of plain `unsigned`? – Some programmer dude Jul 12 '23 at 07:09
  • both would do, but the question still stands, and also - I just read here https://stackoverflow.com/a/4295225/3512538 that `size_t` is preferable – CIsForCookies Jul 12 '23 at 07:10
  • 2
    I think how much you use `auto` is a matter of opinion or style, but these are not necessarily going to be the same thing. – Galik Jul 12 '23 at 07:20
  • 2
    The argument that size_t is "always large enough" doesn't weigh that much if you only need values between 0 and 100. :-) But anyway, with C++23 you get `auto i = 0uz` to get a `size_t` literal. So yet another option. – BoP Jul 12 '23 at 07:41
  • c++23 is far from the c++14 I'm using :( but it's nice to know I'll be able to use that eventually – CIsForCookies Jul 12 '23 at 08:01
  • 3
    You're missing another: `auto num = std::size_t{1};`! This looks a bit strange, yet respect the "[almost always auto](https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/)" moto. – YSC Jul 12 '23 at 08:30

0 Answers0