Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf the ascii char % sometimes gives c and not %

Tags:

c

printf

ascii

I am a little bit confused about how printf treats ascii characters.

When I print the character % like this, I get a correct response like "ascii %", and this is fine.

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

ascii % 

And I can put them on the same line like this, and I get "ascii % %", and that is also fine.

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

ascii % %

But I can't do that in the other order since then I get c and not %, like this "ascii %c"

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

ascii %c

What is happening?

However I noticed that it seems like printf treats \x25 like the normal % sign, since if I add another % directly after the output (\x25%) it becomes what I expect.

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

ascii % %

But then I also noticed that printing a single % also seems to work, but I did not expect it to.

printf("ascii %  \n");

ascii %

Why did this work, I thought that a single % was not a valid input into printf... Could someone clarify how printf is supposed to work?


Note: I am using the default gcc on Ubuntu 12.04 (gcc version 4.6.3).

like image 504
Johan Avatar asked Aug 05 '13 07:08

Johan


People also ask

How to print an ASCII character in C?

Try this: char c = 'a'; // or whatever your character is printf("%c %d", c, c); The %c is the format string for a single character, and %d for a digit/integer. By casting the char to an integer, you'll get the ascii value.

Is ASCII in C?

In C programming, a character variable holds ASCII value (an integer number between 0 and 127) rather than that character itself. This integer value is the ASCII code of the character. For example, the ASCII value of 'A' is 65.

What does printf() do?

The printf() function sends a formatted string to the standard output (the display). This string can display formatted variables and special control characters, such as new lines ('\n'), backspaces ('\b') and tabspaces ('\t'); these are listed in Table 2.1.


1 Answers

In C strings syntax, the escape character \ starts an escape sequence that the compiler uses to generate the actual string what will be included into the final binary. Hence within C source code "%" and "\x25" will generate exactly the same character strings in the final binary.

Regarding the single %, this is an malformed format string. It results in undefined behavior. Therefore

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

is actualy exactly the same as

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

It results in undefined behavior. There's nothing more to do, trying to understand what's happening with single percent characters is a waste of time.

like image 184
Didier Trosset Avatar answered Nov 13 '22 19:11

Didier Trosset