0

When I subtract a larger character with a smaller one, I'm getting a huge positive number instead of a much smaller, negative number, while assigning it to a long long int variable.

If I subtract ' N ' with ' A 'and if I assign it a long long int variable, it turns out to be 18446744073709551605 instead of -13.

When I use abs() function while computing, I get the value correctly, but obviously it will be positive instead of negative. So how to get the value correctly?

char s[] = "ABCT";
char t[] = "PBDI";
long long int curr_diff;
for(int i=0; i<4; i++){
curr_diff = (t[i] - '0') - (s[i] - '0');
printf("Current value : %llu\n", curr_diff);
}

Result from my code

Current value : 15
Current value : 0
Current value : 1
Current value : 18446744073709551605

Expected result

Current value : 15
Current value : 0
Current value : 1
Current value : -11
hrishikeshs
  • 68
  • 2
  • 5

1 Answers1

5

printf("Current value : %llu\n", curr_diff);

You are printing long long unsigned value. Use %lld to get the right output

Wander3r
  • 1,801
  • 17
  • 27
  • 10
    Eliminating the risk of using the wrong format string is a good reason for using `std::cout` over `printf` as it's type safe. – François Andrieux Jan 09 '19 at 16:33
  • 1
    To re-word for clarity: OP is trying to print `long long int` using the specifier that is meant for `unsigned long long int`. The behaviour of the program is undefined. – eerorika Jan 09 '19 at 16:45