Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
928 views
in Technique[技术] by (71.8m points)

c - 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);
              ^
       &      [  ]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...