Search code examples
cclangcompiler-warningsc11

clang: <string literal> + <expression returning int> leads to confusing warning: adding 'int' to a string does not append to the string


This code:

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
  bool flag = true;
  printf("%s\n", "xxxzzz" + ( flag ? 3 : 0 ));
  return 0;
}

compiled with -std=c11 -pedantic leads to warning:

main.c:7:27: warning: adding 'int' to a string does not append to the string
      [-Wstring-plus-int]
  printf("%s\n", "xxxzzz" + ( flag ? 3 : 0 ));
                 ~~~~~~~~~^~~~~~~~~~~~~~~~~~
main.c:7:27: note: use array indexing to silence this warning
  printf("%s\n", "xxxzzz" + ( flag ? 3 : 0 ));
                          ^
                 &        [                 ]
1 warning generated.

However, this code:

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
  bool flag = true;
  printf("%s\n", ("xxxzzz") + ( flag ? 3 : 0 ));
  return 0;
}

compiled with -std=c11 -pedantic leads to no warning.

Why this warning?

Why does the () matter?

P.S. gcc / msvc generate no warnings in both cases.


Solution

  • The warning is simply because the code is non-idiomatic (i.e. unusual use of pointer arithmetic), and people coming from other languages might expect an automatic string conversion of the RHS to create "xxxzzz3" or "xxxzzz0".

    It is the compiler spotting code patterns perhaps common in other languages but which have different and possibly unexpected semantics in C. It is trying to be helpful and prevent common bugs.

    In any case its suggestion to use array indexing semantics is probably the better solution in terms of clear semantics, but using parentheses clearly has the same effect of supressing the warning.