如果我在 printf() 中的字符串后面添加一个带有加号的 int 会发生什么?

问题描述 投票:0回答:3

我已经在一个混淆的程序中阅读了如下代码。

我想知道为什么当我这样做时编译器给我一个警告而不是错误。代码真正想要做什么,为什么编译器建议我使用数组?

#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);
              ^
       &      [  ]
c printf
3个回答
7
投票

考虑一下声明

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()


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


1
投票
printf("hello"+!f);

它实际上在做的是;首先,

!f
的值被添加到字符串“hello”的地址(所以不是添加到值hello,而是添加到指针值)。

这是否有意义取决于

!f
的值。如果它小于该字符串的长度,您将得到一个指向字符串中间某处的指针。如果它大于字符串的长度,它将指向字符串外部,并且尝试访问它将导致未定义的行为(最好的情况是崩溃;最坏的情况是程序中其他地方出现意外行为)。

因为在你的情况下

!f
只是0,它只会输出字符串“hello”。


0
投票

许多编程语言使用加号运算符来连接字符串,例如

"Hello" + " world"
。通常整数会默默地转换为字符串,因此
"num=" + num
可能会按预期工作。 C 是不同的。

正如 Haris 完美解释的那样,你的代码没有错误。所以没有理由发出错误。

但是你的编译器会引起担忧,你是否真的想写下你所写的内容。 Google 会说:您正在将

"hello"
/
"ello"
发送到 printf()。您是指
"hello0"
/
"hello1"
吗?

© www.soinside.com 2019 - 2024. All rights reserved.