c++command-line-argumentsclang++pointer-arithmeticclang-static-analyzer

How to avoid pointer arithmetic when using char** argv


When trying to print the first command line argument:

std::cout << argv[0] << std::endl;

clang-tidy gives the warning:

warning: 'do not use pointer arithmetic' from [cppcoreguidelines-pro-bounds-pointer-arithmetic]

Is there an alternative way to use the values of argv without using pointer arithmetic? Isn't accessing a char** by any sensible method going to have to use pointer arithmetic?

I appreciate there are some specialised functions to handle command line arguments, but they seem too heavyweight for simply printing one argument.

I am writing in c++, using the clang compiler and building with cmake.


Solution

  • From clang-tidy - cppcoreguidelines-pro-bounds-pointer-arithmetic:

    Pointers should only refer to single objects, and pointer arithmetic is fragile and easy to get wrong. span<T> is a bounds-checked, safe type for accessing arrays of data.

    So yes:

    Is there an alternative way to use the values of argv without using pointer arithmetic? Isn't accessing a char** by any sensible method going to have to use pointer arithmetic?

    You're entirely correct. However, the guideline is about hiding that pointer arithmetic, letting a helper class do bounds checks before performing the arithmetic. You can construct a span<char*> from argv and argc. E.g. in C++20 you would write:

    auto args = std::span(argv, size_t(argc));
    

    and then use args instead of argv.