short int vs int
i am reading c++ programing language by bjarne stroustrup edition3
one of its advise in chapter one is : "Prefer a plaint int over short int or a long int"
i cant understand why!? short int use 2 byte however int use 4 so isnt it better to use short int more than int?
First notice that in this forum, there are two threads.One for C and one for C++.Obviously you are not in the right one :)
They are more than two threads of course.
The first one limits your data range and the second one may waste some bits.
Moved to C++ forum (although in hindsight the answer to your question is the same in both C/C++)
2 bytes isn't necessarily better or worse than 4 bytes - it just depends on what you need. If you are working with small numbers and have an extreme need to save space (not common, these days), then a short will suit your needs better (but then so would char, which is essentially a 1-byte int). If you need to work with larger numbers, then a short is worse than an int, and a long int is even better.
All things being equals, 'int' is just a very common, generic type in C, and it basically represents that natural word size of the architecture you're on - so if you're using shorts or longs, you may find that your data is going to get cast to and from ints quite often. Also remember that the size is defined by your implementation - 'long int' and 'int' might actually be the same size.
so you mean using int is faster than short int in 32 bit systems but it may use more space right?
Again, it depends, and it makes no practically no difference for what 99% of people are doing, so 'int' is just more convenient. If I remember correctly, there are different instructions depending on the size of the integer (I've learnt a few assembly languages and none of them terribly well - so maybe I'm wrong), in which case using a short instead of an int would just result in a slightly different instruction - but not necessarily more instructions.
My guess is that if you're ever in a position where this actually makes a noticeable difference to you, you'll either be working on very special hardware or will know the low-level implementation details very well - so I wouldn't worry about which is faster or smaller.
edit: since the exact size is not well defined between different architectures, if the size of an integer makes any different at all to you, you should probably be using types like uint_64, etc. so you know without a doubt what it is. I actually don't remember the last time I saw someone use 'long' and 'short' in real code.