t4 Planeur t4 Planeur - 16 days ago 5
C Question

Print LONG_MIN in C

How I can print LONG_MIN -9223372036854775808 ? (LONG_MAX is working)

#include <unistd.h>

int ft_putchar(int c)
{
return (write(1, &c, 1));
}

void ft_putlnbr(long int n)
{
if (n < 0)
{
ft_putchar('-');
n = -n;
}
if (n >= 10)
ft_putlnbr(n / 10);
ft_putchar((n % 10) + '0');
}


Thank you !

Answer

Embrace the dark side (use the negative side of the long range).

A simple recursive C99/C11 solution:

static void print_long_helper(long n) {
  if (n <= -10) {
    print_long_helper(n / 10);
  }
  putchar('0' - n % 10);
}

void print_long(long n) {
  if (n < 0) {
    putchar('-');
  } else {
    n = -n;  // Make positive numbers, negative - no chance for overflow
  }
  print_long_helper(n);
  puts("");
}

int main() {
  print_long(0);
  print_long(1);
  print_long(-1);
  print_long(INT_MAX);
  print_long(INT_MIN);
  return 0;
}

Output on my 32-bit long machine

0
1
-1
2147483647
-2147483648
Comments