Home > Enterprise >  Why constexpr std::string_view yields "format not a string literal" warning?
Why constexpr std::string_view yields "format not a string literal" warning?

Time:04-29

The following use of constexpr std::string_view produces "format not a string literal" warning:

constexpr std::string_view string_view_format_str = "hello %s";
snprintf(string_view_warning, 100, string_view_format_str.data(), "world");

warning: format not a string literal, argument types not checked [-Wformat-nonliteral]

And doing the following afterwards, doesn't:

constexpr const char * const_char_format = string_view_format_str.data();
snprintf(string_view_warning, 100, const_char_format, "world");

Why constexpr string_view produces that warning?

https://godbolt.org/z/hT6xqhGeW

Both GCC and clang give the same result:

  • GCC (trunk) with -Wformat, -Wformat-nonliteral
  • clang (> 5.0.0) with -Weverything

CodePudding user response:

The warning isn't for string_view, it's for snprintf. That's a C function, and there's no constexpr in C, so it makes sense that GCC didn't bother.

CodePudding user response:

Why constexpr string_view produces that warning?

I don't know.

gcc-11 does not produce such warnings, so this should be a recent enhancement of gcc. As for clang-trunk, it still produces a warning for the second case, which may indicate that it has something to do with the compiler's implementation of diagnostics.

If you need string_view::data() to execute at compile-time, in C 20 you can

consteval auto as_constexpr(auto x) { return x; }

constexpr std::string_view string_view_format_str = "hello %s"
snprintf(
  string_view_warning, 100, 
  as_constexpr(string_view_format_str.data()), 
  "world");

which will suppress gcc-trunk's warnings.

Demo

  • Related