omEchan
omEchan

Reputation: 95

What does '%'%'%' mean and why is it equal to 0?

The following program:

int main()
{
    printf("%d", '%'%'%');
    return 0;
}

Produces the output:

0

I would like to know what is the reason for this.

Upvotes: 1

Views: 197

Answers (3)

chqrlie
chqrlie

Reputation: 144951

'%'%'%' is a purposely obfuscated expression that evaluates to 0 because it is the remainder of the division of '%' by itself.

'%' is a character constant which in C is an integer with type int and an implementation defined value (37 in the ASCII character set used on the vast majority of current systems). Since this value cannot be 0, dividing it by itself evaluates to 1 with a remainder of 0, hence the code prints 0.

Note however that for full portability, the program should end its output with a newline and the printf function should be declared with the proper prototype by including <stdio.h>.

Here is a modified version:

#include <stdio.h>

int main(void) {
    printf("%d\n", '%'%'%');
    return 0;
}

Here are some variations on the same idea:

  • '-'-'-', '^'^'^', '<'<'<', '>'>'>' all evaluate to 0.
  • '/'/'/' and '='=='=' evaluate to 1.
  • '&'&'&'&&'&'&'&' and '|'|'|'||'|'|'|' both evaluate to 1.

Upvotes: 3

anastaciu
anastaciu

Reputation: 23822

The expression prints the remainder of the division of '%' by '%' which is 0. That is the value being printed through "%d" specifier of printf.

Characters are encoded as 8-bit values (in ASCII as an example), character constants, in reallity, have int type in C.

In this case '%' is 37, you are printing the remainder of the division of 37 by 37.

Having '%'%'%' is the equivalent of having 37%37.

Upvotes: 2

dbush
dbush

Reputation: 224387

The second parameter to printf:

'%'%'%'

More easily read as:

'%' % '%'

Is applying the modulus operator % to the characters '%' and '%'. Because characters are encoded as integer values, this is the same as getting the remainder of dividing a number by itself.

Dividing a non-zero number (a printable character cannot have code 0) by itself will always result in a remainder of 0, which is what is being printed.

Upvotes: 7

Related Questions