我在一个混淆的程序中阅读了如下代码。
我想知道为什么编译器在我这样做时给我警告而不是错误。代码真正想做什么以及为什么编译器建议我使用数组?
#include <stdio.h>
int main()
{
int f = 1;
printf("hello"+!f);
return 0;
}
warning: adding 'int' to a string does not append to the string [-Wstring-plus-int]
printf("hello"+!f);
~~~~~~~^~~
note: use array indexing to silence this warning
printf("hello"+!f);
^
& [ ]
最佳答案
考虑语句 printf("hello");
此语句将字符串文字 "hello"
发送到 printf();
函数。
现在让我们分别考虑代码
char* a = "hello";
这将指向存储字符串文字 "hello"
的地址。
如果有人这样做会怎样
char* a = "hello" + 1;
它将使a
指向存储"ello"
的地址。 "hello"+ 1
的地址,指向字符串字面量"ello"
将此应用于您的代码
printf("hello"+!f);
f
的值为 1
。 !f
的值为 0
。所以,最终它会指向字符串文字"hello"+ 0
的地址,也就是"hello"
。然后将其传递给 printf()
。
您没有收到错误,因为它不是错误。
关于c - 当我在 printf() 中的字符串后添加一个带加号的 int 时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33707276/