语句的输出如何 'E'

how is the output of the statement is 'E'

#include <stdio.h>

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

程序的输出是Egcc编译的,请解释

这是因为终止 '[=10=]' 字节,3 + 1 字节所以 "ABCDE"[4]'E'.

此外,main() 的正确签名是

  1. int main(void) 或者,
  2. int main(int argc, char *argv[])

C 标准中的两个引号将使结果清楚。

第一个是关于字符串文字(6.4.5 字符串文字)

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....

第二个是关于隐式转换(6.3.2.1 左值、数组和函数指示符)

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.

所以根据第一个引用,字符串文字 "ABC" 被存储为 char[4] 类型的字符数组(由于附加的零),具有静态存储持续时间。

根据表达式中的第二个引用

sizeof("ABC")

数组未转换为指针。所以实际上这个表达式等同于表达式

sizeof( char[4] )

并产生等于 4.

的结果

所以表达式

"ABCDE" + sizeof("ABC")

可以改写成

"ABCDE" + 4

在这个表达式中,根据第二个引号,代表字符数组本身的字符串文字 "ABCDE" 被转换为指向其第一个元素的指针。于是就有了所谓的指针算法。

您可以通过以下代码片段想象函数调用中表达式的求值结果

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

表达式p + 4指向字符'E',相当于&p[4]&string_literal[4]

注意按照同样的C标准,不带参数的函数main应该声明为

int main( void )

即使函数体中没有 return 语句。

您的程序的输出不是 E,它没有像发布的那样编译,因为 printf("ABCDE" + sizeof("ABC");

中缺少 )

字符串常量的大小是包括空终止符在内的字节数,因此 sizeof("ABC") 的计算结果为 4

"ABCDE" + 4 是字符串中 E 的地址,并且由于字符串在 E 之后没有任何其他字符,因此输出与 printf("E");.

注意 main 没有参数的原型是 int main(void) 并且为了良好的风格,你应该 return 0 并输出一个换行符。

这是您的代码的更正版本:

#include <stdio.h>

int main(void) {
    printf("ABCDE\n" + sizeof("ABC"));
    return 0;
}

输出为

E