|
From: <jar...@ig...> - 2002-06-07 11:59:20
|
On 6 Jun, rchavez wrote:
> Hi,
>
> While trying a problem from my text 'A Book on C' I ran into some strange
> behavior for short integers. If I use integers, the program below reads
> them in & performs the arithmetic correctly. But if I change line 3 so the
> variables are of type short, the value of x is always 0 !!
>
> I've played with it a lot but can't find the problem. Any help would be
> appreciated. Also, notice that the scanf for var ss at the bottom always
> works. It's not a gcc bug since I get the same behavior on a unix compiler.
>
> Rob
>
> /** Math on Short Integers **/
>
> main()
> {
> short x,y, entries=2; /* declared as int program works as expected */
> short ss;
> printf("\n sizeof(short): %d",sizeof(short));
> printf("\n2 to the 15: %d\n\n",128*128*2);
> printf("\n Enter 2 int values: \n");
> entries=scanf("%d",&x);
====================^^ ^
Since x is of type short int you MUST you the input format
%hd . If you write %d scanf inputs 4 bytes and thus overwrites the
2 bytes in storage following x .
Since scanf use a variable parameter list type checking is disabled.
One more reason to avoid the C input/output system.
In C++ the input operator '>>' has no such problems.
The same in the scanf calls below.
> entries +=scanf("%d",&y);
> printf("\n x= %d y= %d",x,y);
>
> while (entries == 2) {
> printf("\n x= %d y= %d",x,y);
> printf("\nX+Y = %d",x+y);
> printf("\nX-Y = %d",x-y);
> printf("\nX*Y = %d",x*y);
> printf("\nX/Y = %d",x/y);
> printf("\nx %c y = %d\n",'\045',x%y);
>
> ss = 64000;
> printf("\nEnter a short int");
> scanf("%d",&ss);
> printf("\n Another try on a short int gives: %d",ss);
> printf("\n Enter 2 int values: ");
> entries=scanf("%d%d",&x,&y);
> }
>
> printf("\n\n");
> system("PAUSE");
> return 0;
> }
>
--
Helmut Jarausch
Lehrstuhl fuer Numerische Mathematik
Institute of Technology, RWTH Aachen
D 52056 Aachen, Germany
|