I answered a question on SO today, however it did't receive any up-votes, so I want to know what's wrong with my code.

The requirement is to compare the input numbers(granted to be positive) without logical, relational or bitwise operators, and insert the corresponding comparison sign between them. For example:

input:  4 6
output: 4 < 6
input:  10 2
output: 10 > 2
input:  2 2
output: 2 = 2

Here is my posted code:

#include <stdio.h>

int main(void)
    unsigned a, b;
    scanf("%u %u", &a, &b);
    printf("%u ", a);
    char relationship[] = {'<', '=', '>'};
    putchar(relationship[!!(a/b) - !!(b/a) + 1]);
    printf(" %u", b);
    return 0;

That OP wants to know how to insert a comparison sign(<, >, =) between the two numbers. But my emphasis is on how to determine the relationship of the two numbers.

See: https://stackoverflow.com/q/35532123/5399734 for the original question.

  • 1
    \$\begingroup\$ Isn't ! considered a logical operator? \$\endgroup\$ – JS1 Feb 21 '16 at 17:38
  • 1
    \$\begingroup\$ Yes, it is. I've improved this code to avoid ! operators. See my posted code on SO: stackoverflow.com/a/35533732/5399734 \$\endgroup\$ – nalzok Feb 21 '16 at 23:06
  • \$\begingroup\$ Should I post the improved code again by editing this question on code review? \$\endgroup\$ – nalzok Feb 21 '16 at 23:08
  • \$\begingroup\$ The C spec has "... the logical negation operator !...". § 5. Using ! does not meet "without logical, relational or bitwise operators" and neither does this answer \$\endgroup\$ – chux - Reinstate Monica Feb 21 '16 at 23:51
  • \$\begingroup\$ @sun qingyao Recommend against editing this code. This is a review of your code - as is. Changing the code invalidates the work done so far. You could post new code in a new question, adding links to this and that post for reference indicating the next one is a follow-on. Maybe including ideas from the review(s) done here. \$\endgroup\$ – chux - Reinstate Monica Feb 21 '16 at 23:57

That seems a fine solution. Some minor suggestions:

  • Instead of spelling out relationship as {'<', '=', '>'}, you could use simply "<=>"
  • Instead of printing a, the relation and b in separate statements, it will be more readable to print in a single printf
  • The expression !!(a/b) - !!(b/a) evaluates to -1, 0, 1, commonly returned by a cmp function. If you give the expression a name by putting it in a variable, that will ring a bell with many readers and make it easier to understand.

Something like this:

unsigned a, b;
scanf("%u %u", &a, &b);

int cmp = !!(a/b) - !!(b/a);
char relation = "<=>"[cmp + 1];
printf("%u %c %u\n", a, relation, b);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.