|
-
January 14th, 2009, 08:58 AM
#7
Re: Size_t Weird Bug within Loop
 Originally Posted by GCDEF
The only thing "completely wrong" in the OP's code is his decision to use an unsigned counter.
That is not so wrong after all. The size_type typedefs over the standard containers and sequences are unsigned types as well. Most implementations will have std::size_t and size_type to be the same (but it may not be guaranteed - I am not sure). Both are unsigned integral types - that's for sure.
So, there's nothing inherently wrong with using that kind of a loop. The only thing wrong is that he unknowingly expects that when his loop counter reaches 0, and is decremented, it will become less than 0 and hence break out of the loop. That is wrong!
Although, alternatives have been provided, here is a fix to that loop:
Code:
for (std::size_t loop = obj.size() - 1; loop < obj.size() ; --loop)
{
std::cout << obj[loop] << "\n";
}
Can you help me with my homework assignment?, Before you post!, Use code tags, How to post!, Codeguru technical FAQs, C++ FAQ Lite, Stroustrup: C++ Style and Technique FAQ, Guru of the Week, Comeau C and C++ FAQs, Comeau C++ Templates FAQs, CUJ @ DDJ, Spam threshold
My Blogs : Learning C++ is fun | Abnegator's reflections
Open Threads : C++ Aha! Moments | Nature of work in C++?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|