Printf ascii char% sometimes gives c, not%

I'm a little confused about how printf handles ascii characters.

When I print the% character like this, I get the correct answer, like "ascii%", and that’s fine.

printf("ascii %% \n"); printf("ascii \x25 \n"); printf("ascii %c \n", 0x25); ascii % 

And I can put them on one line like this, and I get "ascii %%", and that is fine too.

 printf("ascii %c \x25 \n", 0x25); ascii % % 

But I can't do it in a different order, since then I get c, not%, like this "ascii% c"

 printf("ascii \x25 %c \n", 0x25); ascii %c 

What's happening?

However, I noticed that it seems that printf treats \ x25 as a regular% sign since if I add another% immediately after the exit (\ x25%), it will become what I expect.

 printf("ascii \x25% %c \n", 0x25); ascii % % 

But then I also noticed that printing one% also works, but I did not expect this.

 printf("ascii % \n"); ascii % 

Why is this work, I thought that one% is not a valid contribution to printf ... Can anyone clarify how printf should work?


Note. I use gcc by default for Ubuntu 12.04 (gcc version 4.6.3).

+6
source share
3 answers

In C string syntax, the escape character \ launches the escape sequence that the compiler uses to generate the actual string that will be included in the final binary. Therefore, in the C source code, "%" and "\ x25" will generate exactly the same character strings in the final binary format.

As for the only % , this is an invalid format string. This leads to undefined behavior. therefore

 printf("ascii \x25 %c \n", 0x25); 

relevant just like

 printf("ascii % %c \n", 0x25); 

This leads to undefined behavior. There is nothing more to do, trying to understand what happens to characters with one percent - this is a waste of time.

+7
source

Yes, printf treats \ x25 as the usual% sign, printf("ascii % \n"); works because % is at the end of the format string (ignoring spaces).

+2
source

printf("ascii \x25 %c \n", 0x25); format printf("ascii \x25 %c \n", 0x25); since, as you expected, \ x25 exactly matches the '%' character, this is {percent} {space} {percent} {c}. therefore, it prints a percent sign with the leading space, then c.

[edit: there is no starting space, as I said, since "c" is not a numeric qualifier] [edit 2: the argument ", 0x25" is ignored, because there is no corresponding qualifier for using it]

+1
source

Source: https://habr.com/ru/post/951018/


All Articles