当我在printf()中的字符串后面添加带加号的int时会发生什么

ped*_*dim 1 c printf

我已经在一个混淆程序中读了下面的代码.

我想知道为什么编译器在我这样做时给了我一个警告而不是一个错误.代码真正想做什么以及为什么编译器建议我使用数组?

#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);
              ^
       &      [  ]
Run Code Online (Sandbox Code Playgroud)

Har*_*ris 7

考虑一下这句话 printf("hello");

此语句将字符串文字发送"hello"printf();函数.


让我们现在分别考虑代码

char* a = "hello";
Run Code Online (Sandbox Code Playgroud)

这将指向"hello"存储字符串文字的地址.

如果一个人怎么办

char* a = "hello" + 1;
Run Code Online (Sandbox Code Playgroud)

它将a指向"ello"存储的地址.地址"hello" + 1,指向字符串文字的地址"ello"


将此应用于您的代码

printf("hello"+!f);
Run Code Online (Sandbox Code Playgroud)

f有价值1.!f会有价值的0.所以,最终它将指向字符串文字的地址"hello" + 0,即"hello".然后传递给printf().


您没有收到错误,因为它不是错误.