简体   繁体   中英

Using short and long instead of int and double (C++)

Is there a benefit in using short and long instead of int and double? Other than int and double taking up more storage? My professor penalizes code that uses int and double with no explanation. I have not really found a good reason for it in the few textbooks I am using. Where can they be more useful? For example, this one of many functions in my code

    void randDir(int& x, int& y){
            do{
                x = rand() % 4 - 1;
                y = rand() % 4 - 1;
                if(x == 2) x=0;
                if(y == 2) y=0;
            }while(x == 0 && y == 0);
  }  

And this is what my professor wanted

    void randDir(short& x, short& y){
    do{
        x = rand() % 4 - 1;
        y = rand() % 4 - 1;
        if(x == 2) x=0;
        if(y == 2) y=0;
    }while(x == 0 && y == 0);
}

The only advantage of using short is that it takes up less space. If you're programming for a very memory-tight environment, or you have a large array of numbers, or your data will leave the program's address space ( eg, to be saved to disk or transmitted across a network) then this might be important. In other cases, using types other than int unnecessarily might actually slow down your program due to the way processor architectures are designed. See for example:

If you need a type that has exactly the size you think short has, in order to store some bit pattern or something like that, you should be using one of the exact-width types such as std::int16_t , not short . So that's usually not a valid reason for using short .

It's possible that your C++ instructor learned to code a long time ago in an environment where every byte counts, and mistakenly believes that that's still the case nowadays. Sadly, this kind of preconceived notion is very common. (Other symptoms include forbidding exceptions and forbidding the use of standard library containers). In such cases you should generally be aware of the fact that smart people can often say stupid things. Stack Overflow is a good place to get information about current best practices, as are the books listed here: The Definitive C++ Book Guide and List

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM