unsigned int vs. size_t: what's the difference and which is better to use in C++?
Hi colleagues. I'm a beginner C++ developer, and I can't wrap my head around the difference between `unsigned int` and `size_t`. They both seem to be unsigned integer types, but I constantly see one used in some places and the other in others. \n\nFor example, I'm writing a simple program to count elements in a vector:\n\n```cpp\n#include \n#include \n\nint main() {\n std::vector numbers = {1, 2, 3, 4, 5};\n unsigned int size = numbers.size(); // Compiles, but a warning?\n for (unsigned int i = 0; i < size; ++i) {\n std::cout << numbers[i] << std::endl;\n }\n return 0;\n}\n```\n\nThe compiler gives a warning about type mismatch in the comparison `i < size`, even though both seem to be `unsigned int`. But if I write `size_t size = numbers.size();`, everything is fine.
No answers yet.
Log in to leave an answer