简体   繁体   中英

overflow short int in language C

I'm trying to make a program that show short int overflows in C. In my program you enter two short int and I add them. If the addition is superior to 32767 we have a negative overflow and if the addition is inferior to -32678 we have a positive overflow.

Now my problem is that my program refuses to respect any of the condition when using if . But when I use do while my program consider that I respect the two condition at the same time.

short int n1, n2, somme;
printf("Enter the first number: ");
scanf("%hi", &n1);
printf("enter the second number : ");

scanf("%hi", &n2);

somme= n1 + n2;
    do
    {
    printf("negative overflow\n");
    }while (somme>32767);
    do
    {
    printf("negative overflow\n");
    }while ( somme<-32768);

printf("the result is %hi", somme);

Sorry for my english. and thanks for reading, please help.

I made a few changes in your code to demonstrate what you were trying to do,

#include<stdio.h>
int main(){
    short int n1, n2, somme;
    printf("Enter the first number: ");
    scanf("%hi", &n1);
    printf("Enter the second number : ");
    scanf("%hi", &n2);

    somme = n1 + n2;
    if( (n1 + n2) > 32767)
        printf("negative overflow\n");
    else if ( (n1 + n2) < -32768)
        printf("positive overflow\n");

    printf("int addition result is %d\n", n1 + n2);
    printf("short addition result is %hi\n", somme);
    return 0;
}

And here is the output,

Enter the first number: -20000
Enter the second number : -20000
positive overflow
int addition result is -40000
short addition result is 25536
-----------------------------
Enter the first number: 20000
Enter the second number : 20000
negative overflow
int addition result is 40000
short addition result is -25536

So, what was wrong in your code is that,

  • You were using do...while to check for conditions. Use if-else .
  • You were storing the sum in short and comparing that with -32768 and 32767 . You are trying to check if your sum overflowed by comparing it with values which are outside the range of values it can hold. This is also explained by Jérôme Leducq in his answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM