void main() { printf(2 + "abcdefgh"); } How does this code print c...">

Using (+ ve integer) + "some string" in printf?

#include <stdio.h>

void main() {
    printf(2 + "abcdefgh");
}

      

How does this code print cdefgh

? The compiler throws an error if I use 2-

or 2*

or any other operator.

+3


source to share


2 answers


When using string literals such as "abcdefgh"

, you actually have a pointer to the section in memory where that string resides. Basically you go to a printf

pointer to that location and instruct it to move the pointer 2 locations forward, resulting in a line that starts at the 3rd char rather than the first

Note that you can use -

, but you need to use it in the same way as for pointer arithmetic like

printf("abcdefgh" - 0); // using -N where N >0 would be UB



So this code is valid

int main()
{
    printf("abc\n" - 0);
    printf(1+"def");
    return 0;
}

      

but usage *,/

won't (also bitwise operators |,&

won't be valid)

+2


source


In this code

printf(2 + "abcdefgh");

      

coincides with

printf(&("abcdefgh"[2]));

      

where argument serves as a format string in printf()

.

To develop from properties of string literals citing C11

, chapter ยง6.4.5 / P6



In phase 7 translation, a byte or code of zero value is added to each multibyte the character sequence that is obtained from the string literal or literals. 78) Multibyte character sequence is used to initialize an array of static storage duration and length sufficient to contain the sequence. For character string literals, array elements have a type char

and are initialized with individual bytes of a multibyte character sequence. [...]

and for an array, from chapter ยง6.3.2.1,

Unless it is an operator operand, operator sizeof

, _Alignof

or unary operator, &

or string literal used to initialize an array, an expression that is of type `` of type type is converted to an expression with a type pointer '' to type such points to the original element of the array object, and is not an lvalue. [...]

so in the case of a function call argument as one of the arguments of the addition operator, the string literal is actually reduced to the address of the first element in the literal, followed by addition, which is pointer arithmetic . The result is an incremental pointer that points to the third element (C arrays are a 0-based index).

However, as highlighted in the previous paragraph, pointer arithmetic is only valid for additive operations, not multiplicative operators.

+3


source







All Articles