Home > Back-end >  I get wrong and signed value in 'C' language
I get wrong and signed value in 'C' language

Time:06-19

I am using Turbo C .

This is code:

#include<stdio.h>
#include<conio.h>
void main()
{
 clrscr();
 
 printf("%d",1000*100);
 printf("\n%d",1000*10);

 getch();
}

Output:

-31072
10000
  1. Why does the first printf() give wrong and signed value? Whether integer have range (-2147483648 to 2147483647).

  2. And in second printf() it gives right value with right sign. How?

CodePudding user response:

1000*100=100'000. If your int is 16-bits-long, then the result is higher than the maximum supported value, which is 32'767. If you're running a 32-bit OS or you're making a 32-bit program, consider using "long", which is 4 bytes in the case of 32-bits OSs or 8 bytes for 64-bit ones; the highest supported value will respectively be: 2'147'483'647, 9'223'372'036'854'775'807. To have a long as an output, use one of the following format specifiers: %l, %ld or %li. To see the maximum value for int, include limits.h and check (see the last source).

Hope it helps.

Sources:

CodePudding user response:

You are having an integer overflow.

Turbo C/C is a 16-bit compiler. It is not used for development. Stop using it as soon as you can.

The int type can store values between -32768 and 32767. The following program demonstrates.

#include<stdio.h>
#include<conio.h>

void main()
{
    int i;
    clrscr();
    for(i = 0; i >= 0; i  );
    printf("%d\n", i); // upper limit of int
    printf("%d\n", i - 1); //lower limit of int
    getch();
}

To get the answer you want, you need to cast that number to long.

printf("%d",1000*100);

should be

printf("%ld", (long)1000*100);

See it in action at OnlineGDB.

  • Related