2

I am using the following code in a small program demonstrating expression behavior:

c = a % b;
d = b % a;
printf("\nc = a % b\n"
       "d = b % a\n"
       "  a = %d\n"
       "  b = %d\n"
       "  c = %d\n"
       "  d = %d\n\n",
       a, b, c, d);

This is outputting as follows:

c = a % b
d = b  0x0.0000000000008p-1022
  a = 5
  b = 7
  c = 5
  d = 2

I have tried escaping the modulo operators in the string with no change in the output:

c = a % b;
d = b % a;
printf("\nc = a \% b\n"
       "d = b \% a\n"
       "  a = %d\n"
       "  b = %d\n"
       "  c = %d\n"
       "  d = %d\n\n",
       a, b, c, d);

What I'm wondering is: why would % a seem to point to a place in memory when % b outputs as expected as a string? Additionally, why would escaping the modulo symbol not resolve the issue?

Edit (resolved):

Thanks everyone for the comments and answers; I was able to find the full details from your resonses.

This question is a duplicate of the following which can be referenced for more information:

White space is ignored following % and printf will use the next non-white space character to identify a conversion specifier. The reason this did not effect "c = a % b" is because %b is not a valid conversion specifier.

The reason %% must be used to escape the % symbol is because %'s usage here is specific to printf and must follow the escape rules of printf, which differ from the escape rules of \ inherited from C.

Jacquelyn
  • 23
  • 4
  • 4
    Possible duplicate: https://stackoverflow.com/q/32095786/10871073 TL;DR: To print a `%` character with `printf` you need to specify `%%`. – Adrian Mole Jan 23 '22 at 21:12
  • 1
    Reading the [printf manual](https://www.man7.org/linux/man-pages/man3/printf.3.html) will tell you that `%a` is a conversion specifier whereas `%b` is not. – kaylum Jan 23 '22 at 21:13

1 Answers1

2

To escape the symbol '%' in the format string you need to double it like

printf("\nc = a %% b\n"
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335