G
G
German2019-03-25 23:04:07
C++ / C#
German, 2019-03-25 23:04:07

What to use, size_t or int in a for loop?

Everyone uses int in counting loop iterations, and now I read that it makes the program incompatible with x64 architecture when processing large arrays and that it is better to use size_t. It's right?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
longclaps, 2019-03-25
@longclaps

Do you have large arrays? Very very?
Don't fill your head with bullshit. Int is fine.

T
tsarevfs, 2019-03-26
@tsarevfs

Use solutions in the following priority:
1. ready-made stl algorithm (e.g. std::find, std::remove_if,...)
2. range based for "for (const auto& elem : myArray)"
3. for (auto iter = myArray .begin()...
4. int
5. size_t
The main problem with int is the annoying warning about comparing signed and unsigned types in
i < array.size() std::ssize from C++20, which returns int Arrays larger than int are too rare to choose a default solution based on them.
Unsigned types lead to a lot of errors associated with negative numbers. Ideally, they should only be used where controlled overflows are needed (modulo 2^{32,64} operations). A simple example where you can shoot yourself in the foot is the cycle from 10 to 0.

M
Melkij, 2019-03-25
@melkij

Choose the data type that you really need.
If you have a maximum of a couple of million iterations in the loop, then why do you need a 64-bit integer?
If a 32-bit number is really not enough for you, then you cannot use either int or size_t for these purposes, you must use a 64-bit platform-independent integer.
And if you have a couple of dozen iterations in a jump, then int is too big for you, take something smaller.
Different tasks need different types of data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question