Domanda

The type int is 4-byte long and I wrote a little procedure in C under Ubuntu to print the number I've just input. When I input 2147483648, i.e. 2^31, it prints 2147483647 rather than -1. The same thing happens when I input any number larger than 2147483647. Why doesn't it overflow to -1 as I learnt form book but seems like truncated to INT_Max and what happened in the bits level?

#include <stdio.h>
int main(){
  int x;
  scanf("%d",&x);
  printf("%d\n",x);
}

I made a mistake. INT_Max+1 should equal to INT_Min. I modified the code:

#include <stdio.h>
int main(){
  int x=2147483647;
  int y=x+1;
  printf("%d",y);
}

and the output is -2147483648 Now I'm just wondering what happened when I call the function scanf? I think it truncated all the input number larger than 2147483647 to 2147483647.

È stato utile?

Soluzione 2

The representation of 2147483647 ie INT_MAX is 0x7FFFFFFF.
If you add 1, you'll get an undefined behaviour.
This said, in practice, if you add 1, you'll get 0x80000000 ie -2147483648.
I don't know why you expect -1 as its binary encoding is 0xFFFFFFFF.

#include <stdio.h>
#include <errno.h>

int main(){
  int val1 = 2147483647;
  int val2 = val1+1;
  int x;

  printf("errno before : %d\n",errno);
  scanf("%d",&x);                        //enter 2147483648 or a larger value
  printf("errno after : %d\n\n",errno);

  printf("val1 = %d (0x%X)\n", val1, val1);
  printf("val2 = %d (0x%X)\n", val2, val2);
  printf("x    = %d (0x%X)\n", x, x);

  return 0;
}

Output :

errno before : 0
errno after : 34 //0 if the entered value is in the range of 4-bytes integer

val1 = 2147483647 (0x7FFFFFFF)
val2 = -2147483648 (0x80000000)
x    = 2147483647 (0x7FFFFFFF)

The reason why you get x=2147483647 is that scanf clamps the value to the possible range.
If you check errno after scanf call, you will see that it is equal to ERANGE (code 34)

Altri suggerimenti

By the C99 standard 6.5 Expressions:

If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.

See here:

int i = 2147483648;
printf("%d",i);

http://ideone.com/07THjV

void main()

By the way main returns int.

You can read input in hexadecimal and will get proper output

int main(void) {
int a;

printf("\nEnter number :"); scanf("%X",&a);
printf("\n\n%d\n\n",a);

    return 0;
}

input value : 80000000
Output will be :-2147483648
OR you can use like this

printf("\nEnter number :"); scanf("%u",&a);

input value : 2147483648
Output will be :-2147483648

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top