Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

c++ - When to use `short` over `int`?

There are many questions that asks for difference between the short and int integer types in C++, but practically, when do you choose short over int?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(See Eric's answer for more detailed explanation)

Notes:

  • Generally, int is set to the 'natural size' - the integer form that the hardware handles most efficiently
  • When using short in an array or in arithmetic operations, the short integer is converted into int, and so this can introduce a hit on the speed in processing short integers
  • Using short can conserve memory if it is narrower than int, which can be important when using a large array
  • Your program will use more memory in a 32-bit int system compared to a 16-bit int system

Conclusion:

  • Use int unless you conserving memory is critical, or your program uses a lot of memory (e.g. many arrays). In that case, use short.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...