question

int vs double vs short

i understand that computers dont really have limited memory problems, so what is the standard that everyone uses now?
Last edited on
The choice between integer types and floating point types depends on what you use it for. If you are storing integers you should prefer an integer type. Floating point types are great if you want to store decimal numbers but they have limited precision and can have rounding errors so if you use them you should not expect the result to be exact.

double is the standard floating point type in C++ so that is what I use.

int is the standard integer type in C++ so that is often my preferred choice, but it depends on the range of values I want to store. If it's a member variable of some class that I will have thousands of instances of I might choose a smaller type to save some memory. If I think I need a larger type I use that. If I don't need negative values I sometimes use an unsigned type but I'm afraid I'm not very consistent because mixing types can be a pain.

When using integer types other than int (and unsigned int), or If I care about the exact size, I often use one of the fixed width integer typedefs in <cstdint> to be sure I get the correct size. short, int, long, etc. can all have different sizes depending on the compiler. Using std::uint64_t I can be sure the type is a 64-bit unsigned integer.
http://en.cppreference.com/w/cpp/header/cstdint

When storing indexes and sizes of containers I use std::size_t.
1
2
3
4
for (std::size_t i = 0; i < vec.size(); ++i) // if I used an int (or some other signed type)
{                                            // the compiler would have thrown me a warning.
	std::cout << vec[i] << std::endl;
}
Last edited on
good info! Thank you!
Topic archived. No new replies allowed.