Search code examples
carraysimplicit-conversionstring-literalspointer-arithmetic

how is the output of the statement is 'E'


#include <stdio.h>

main() {
    printf("ABCDE" + sizeof("ABC");/*please explain the output*/
}

Output of the program is E compiled with gcc, please explain


Solution

  • Two quotes from the C Standard will make the result clear.

    The first one is about string literals (6.4.5 String literals)

    6 In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.78) The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence....

    And the second one is about implicit conversions (6.3.2.1 Lvalues, arrays, and function designators)

    3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

    So according to the first quote the string literal "ABC" is stored as a character array of the type char[4] (due to the appended zero) with the static storage duration.

    According to the second quote in the expression

    sizeof("ABC")
    

    the array is not converted to a pointer. So in fact this expression is equivalent to the expression

    sizeof( char[4] )
    

    and yields the result equal to 4.

    So the expression

    "ABCDE" + sizeof("ABC")
    

    can be rewritten like

    "ABCDE" + 4
    

    In this expression according to the second quote the string literal "ABCDE" that represents itself a character array is converted to the pointer to its first element. Thus there is used the so-called pointer arithmetic.

    You can imagine the result of the evaluation of the expression in the function call with the following code snippet

    char string_literal[6] = "ABCDE";
    char *p = &string_literal[0];
    printf( p + 4 );
    

    the expression p + 4 points to the character 'E' and equivalent to &p[4] or &string_literal[4]

    Pay attention to that according to the same C standard the function main without parameters shall be declared like

    int main( void )
    

    even though a return statement is absent in the function body.