Thread: signed or unsigned for loop counters?

  1. #1
    Old Fashioned
    Join Date
    Nov 2016
    Posts
    137

    Question signed or unsigned for loop counters?

    I've for a while been in the habit of using size_t for my loop counters like this:

    Code:
    size_t i;
    
    for(i = 0; i < 500; i++)
    {
      //do stuff
    }
    My reasoning behind this is that many of the critical std lib functions like malloc, memcpy, and so on take size_t, and strlen() returns size_t.

    My other big reason is that logically, when I think of my counter, I think of it being a number 0 or greater. I never employ counters which need to have negative numbers.

    Is this practice of mine good? Why or why not? What type do you typically use for your counters? If all else fails, assume we're talking about situations where the counter is being compared with a integer in the set 0 to 64 bit max.
    If I was homeless and jobless, I would take my laptop to a wifi source and write C for fun all day. It's the same thing I enjoy now!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,550
    Yes, it makes sense when you're dealing with indices, though you have to be careful if you're looping from N-1 to 0 rather than the usual 0 to N-1.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Signed and unsigned
    By ncode in forum C Programming
    Replies: 3
    Last Post: 09-02-2011, 08:59 PM
  2. Unsigned vs. Signed?
    By Programmer_P in forum C++ Programming
    Replies: 4
    Last Post: 12-22-2009, 01:15 PM
  3. Signed and unsigned
    By alyeska in forum C++ Programming
    Replies: 5
    Last Post: 09-18-2007, 12:27 PM
  4. signed or unsigned?
    By ulillillia in forum C Programming
    Replies: 7
    Last Post: 05-08-2007, 01:06 AM
  5. Signed vs Unsigned int
    By osyrez in forum C++ Programming
    Replies: 18
    Last Post: 08-17-2006, 07:38 AM

Tags for this Thread