简体   繁体   中英

What happens when I adding an int with a plus sign after the string within printf()

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);
              ^
       &      [  ]

Consider the statement printf("hello");

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


Lets now separately consider the code

char* a = "hello";

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

What if one does

char* a = "hello" + 1;

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"


Apply this to your code

printf("hello"+!f);

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("hello"+!f);

What it is actually doing is; first the value of !f is added to the address of the string "hello" (so not to the value hello, but to the pointer value).

Whether or not that's meaningful depends on the value of !f . If it's less than the length of that string, you'll get a pointer that points somewhere in the middle of the string. If it's larger than the length of the string, it'll point outside the string and an attempt to access it will result in undefined behavior (at best, a crash; at worst, unexpected behavior elsewhere in your program).

Since in your case !f is just 0 it will just output the string "hello".

Many programming languages use the plus operator to concatenate strings, like "Hello" + " world" . Often integers silently converted to strings, so "num=" + num might work as intended. C is different.

As Haris perfectly explained, your code is not wrong. So there is no reason to issue an error.

But your compiler raises concerns, whether you really meant what you have written. Google would say: You are sending "hello" / "ello" to printf(). Did you mean "hello0" / "hello1" ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM