You do not need to use decltype(s.size()) to declare a type, but declaring it as an int not necessarily a good idea. Or at least it's not a good habit to join.
decltype(s.size()) literally means that "this type should be the same as std::string uses to store the length of a string." In most C ++ implementations, this is size_t , which will be either an unsigned 64-bit integer (in most cases) or an unsigned 32-bit integer. In any situation, int (which is signed and probably will not be 64-bit) will not represent the entire possible range of sizes for std::string objects, which in exotic situations can be more than 2.1 billion characters. In such situations, if you define a type as int , you risk undefined behavior.
Please note that in my code I just simply write for(size_t index = 0; index < string.size(); index++) , because it is simpler. But if you want to guarantee that the code will behave on all platforms, for(decltype(string.size()) index = 0; index < string.size(); index++) is the safest version of the code.
Xirema
source share