Hi,
I noticed a few snippets recently where a size_t variable was used for array indices, and after searching around I'm still not sure what the obvious advantage of using a size_t variable over a typical int would be..

To clarify, what would be the difference between this:

for(size_t i=0;i<5;i++)
//do something with arr[i]

..and this:

for(int i=0;i<5;i++)
//do something else with arr[i]

Is it worth using size_t variables in fairly generic, simple console apps etc or do it's advantages (if any) only become apparent at a much higher level of complexity..?

Not urgent, was just interested :)

portability :

"The actual type of size_t is platform-dependent; a common mistake is
to assume size_t is the same as unsigned int, which can lead to
programming errors, particularly as 64-bit architectures become more
prevalent"

commented: ..just what I was looking for. +1

Some c++ stl classes, such as string, vector, and list, return size_t in some of its methods. For example. std::vector size() returns size_t value. Some compilers (such as Microsoft) will produce warnings if you attempt to compare size_t with int or long.

Thanks for the responses.
So then the main advantage is portability..
Does that mean that size_t variables will literally be different sizes on 32-bit and 64-bit systems? And is it common practise to use them for array indices?

It gets worse than that -- the size could be different between compilers on the same os and between operating systems.

OK, guess I'll start using them regularly then. Thanks for all the replies.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.