Pelles C forum

C language => Beginner questions => Topic started by: joselitosn on April 02, 2007, 04:35:02 PM

Title: Strange Behaviour?
Post by: joselitosn on April 02, 2007, 04:35:02 PM
What's wrong with using "short int" in this code?
Quote
#include <stdio.h>
#include <conio.h>
#include <math.h>

double hypotenuse( short int cat_a, short int cat_o );

int main( void )
{
   short int ca, co;

   printf("First cathetus:\n");
   scanf("%d", &ca );

   printf("Second cathetus:\n");
   scanf("%d", &co );

   printf("The hypotenuse of the triangle is %.2f .\n", hypotenuse( ca, co ));

   getch();
   return( 0 );
}

double hypotenuse( short int cat_a, short int cat_o )
{
   double hip, x, y;

   printf("%d\n", cat_a );
   printf("%d\n", cat_o );
   x = pow((double) cat_o, 2 );
   y = pow((double) cat_a, 2 );
   hip = x + y;

   return( sqrt( hip ));
}

The printf show that the variable ca is not passed, even if change it's position inside the hypotenuse call.

It's something related to it being 16-bit? Also it didn't work well with another compilers. Ch Interpreter and lcc-win32 worked, but lcc throws an exception at the end.

Of course changing to "int" work, but i just didn't understand why. Also if i declare "short int ca[2]" and use it as arguments, it works without a problem (except lcc which throws an exception again at the end).
Title: Re: Strange Behaviour?
Post by: cane on April 02, 2007, 05:04:35 PM
Prepend "%d" type character with "h" argument-type modifier both in scanf() and printf() calls, that is: use the string "%hd".
Title: Re: Strange Behaviour?
Post by: AlexN on April 03, 2007, 07:44:07 AM
Of course changing to "int" work, but i just didn't understand why. Also if i declare "short int ca[2]" and use it as arguments, it works without a problem (except lcc which throws an exception again at the end).

The problem is, that printf does not know the format (size) of the parameters behind the format-string. With %d you say there comes an integer. If you use a compiler where short int and int have a different size, your code will not work.