Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

`% a` in string reads as a point in memory

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

printf("\nc = a %% b\n"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading