This statement involving pointer arithmetic is UB, because of the associativity of +
operator.
In this case (considering ASCII encoding)
g[6]
is o
, which has a decimal value of 111
g[8]
is g
, which has a decimal value of 103
So, finally the construct looks like
printf("%s", g + 'o' - 'g');
which is same as
printf("%s", (g + 111) - 103);
here, g+111
points way past the array (note: arithmetic involving only one element past the array is valid), so this would be UB.
However, if we modify the statement like
printf("%s", g + (g[6] - g[8])); //enforcing precedence
which is same as
printf("%s", g + 8);
or
printf("%s", &(g[8]));
then it will be valid. However, if there's other encoding systems in use, and (g[6] - g[8])
does not yield a value which is within the array bounds, it'll again be UB for the same reason as the original statement.