user3073850 - 8 months ago 43

C Question

I am trying to solve flowing problem:

You are given an integer called n.

print '+' if n is positive,

print '-' if n is negative,

print '0' if n is zero.

write a c\c++ solution without using a single if!

I wrote this code:

`int n;`

scanf("%d", &n);

! n >> (sizeof(n) - 1) && printf("-") || return 0;

n > 0 && prtintf("+") || return 0;

printf("0");

retuen 0;

but i get error: expected primary-expression before 'return' for line 3 and 4.

how can I change this code to make it work!

p.s: using ? : operator is considered cheating!

Answer Source

Yes, it is doable (with some restrictions).

```
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// Assuming 2s-complement numbers
// and an understanding compiler
// Some checks omitted!
int main(int argc, char **argv)
{
int input;
unsigned int itmp;
int size;
int sign, sin, sout;
char out[3] = { '0', '+', '-' };
if (argc != 2) {
fprintf(stderr, "Usage: %s integer\n", argv[0]);
exit(EXIT_FAILURE);
}
// TODO: use strtol and check input!
input = atoi(argv[1]);
size = sizeof(int) * CHAR_BIT;
itmp = (unsigned int) input;
sin = itmp >> (size - 1);
sign = sin ^ 1;
// now "sign" is either 0 (negative) or 1 (positive)
// but we need 1 (negative) and -1 (positive)
// 0 * -2 + 1 = 1
// 1 * -2 + 1 = -1
sign = sign * -2 + 1;
// Now we can do
// in sign out sin sout
// -x * 1 = -x -> 1 + 1 = 2
// +x * -1 = -x -> 0 + 1 = 1
// 0 * -1 = 0 -> 0 + 0 = 0
itmp = itmp * sign;
sout = itmp >> (size - 1);
sign = sin + sout;
printf("Input: %c\n", out[(size_t) sign]);
exit(EXIT_SUCCESS);
}
```

No conditional expressions, neither explicit with `if`

, nor implicit with `while`

or `for`

, nor the shortcut `...?...:...`

.