当我在 printf() 中的字符串后添加一个带加号的 int 时会发生什么 [英] What happens when I adding an int with a plus sign after the string within printf()

查看:55
本文介绍了当我在 printf() 中的字符串后添加一个带加号的 int 时会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have read the code like the one down below in an obfuscated program.

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

I wonder why the compiler gave me an warning instead of an error when I doing like this. What the code really want to do and why the compiler suggests me to use an array?

#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(); 函数.

This statement sends the string literal "hello" to the printf(); function.

现在让我们单独考虑代码

Lets now separately consider the code

char* a = "hello";

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

This would point to an address where the string literal "hello" is stored.

万一呢

char* a = "hello" + 1;

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

It will make a point to an address where "ello" is stored. Address of "hello" + 1, which points to address of the string literal "ello"

将此应用于您的代码

printf("hello"+!f);

f 的值为 1.!f 的值为 0.因此,最终它将指向字符串文字 "hello" + 0 的地址,即 "hello".然后将其传递给 printf().

f has value 1. !f will have value 0. So, eventually it will point to the address of the string literal "hello" + 0, which is "hello". That is then passed to the printf().

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

You are not getting an error because it is not an error.

这篇关于当我在 printf() 中的字符串后添加一个带加号的 int 时会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆