NO

Author Topic: Strange Behaviour?  (Read 2967 times)

joselitosn

  • Guest
Strange Behaviour?
« 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).

cane

  • Guest
Re: Strange Behaviour?
« Reply #1 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".

Online AlexN

  • Global Moderator
  • Member
  • *****
  • Posts: 391
    • Alex's Link Sammlung
Re: Strange Behaviour?
« Reply #2 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.
best regards
 Alex ;)