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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...