Do C++ developers commonly count on automatic casting? : I've been given the task of porting a Windows program to OS X. Originally written in C++, I'm enjoying it because I don't often work with the C family of languages, and have enjoyed making use of Objective C++ in the port.

However, the Windows source code does something strange, and I'm wondering if it's a standard practice. The API we're working with on both Windows and OS X expects a particular object method to be passed an unsigned short. The original Windows developer created the following function to calculate this value:

    static unsigned short hashcode ( const char* value ) {
      int h = 0 ;
      unsigned long length = strlen ( value ) ;
      
      for ( int i = 0 ; i < length ; i++ ) {
        h = ( 31 * h ) + value[i] ;
      }    
      
      return h ;
    }

Note that while the function returns an `unsigned short`, the variable it's returning is declared as an `int`. I've checked the documentation, and both OS X and Windows define an `unsigned short` as 2 bytes and an `int` as 4.

The value being passed to this function, if the data type isn't taken into account, results in the function returning very large numbers, dozens of digits in some cases. In one case, where I duplicated the algorithm in another language with less strict types, I got a value of `2081357292912430390912`. When I wraped the above function in a command line utility, the same string returned a value of `40576`, I'm guessing because that's the truncated version of the longer value.

So I have two questions. First of all, why, if `hashcode` is declared to return an `unsigned short` and it's in fact returning and `int` doesn't the compiler complain? Isn't that what strict data type declarations are for in the first place? To make sure that functions and methods receive and return the data types expected?

And second, is this truncation a standard practice? It seems very strange to me, first of all to take advantage of the automatic casting, but also there's no commenting to call out to someone that that's what's happening (and I don't have access to the original developer to ask). Since it isn't commented as being something "special," perhaps it's simply a standard idiom in C/C++?