Execution of statements in a loop condition

This is a discussion on Execution of statements in a loop condition within the C Programming forums, part of the General Programming Boards category; I have for loop that increments through all of the elements inside of an array. If I use the code: ...

  1. #1
    Registered User
    Join Date
    May 2009
    Location
    Look in your attic, I am there...
    Posts
    92

    Execution of statements in a loop condition

    I have for loop that increments through all of the elements inside of an array. If I use the code:

    Code:
        for(int i = 0;i < strlen(Buffer);i++)
    Is the "strlen(Buffer)" executed every loop? And if so, would it be less overhead if I used a variable to store it?

    Code:
        int Length = strlen(Buffer);
        for(int i = 0;i < Length;i++)

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,451
    Yes and yes. Each strlen() call requires going character by character through the string looking for a '\0'. It's like having a mini for loop in your for loop condition.

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    261
    It's better to assign it to a local variable before you start the loop for two reasons.

    1) it's not executed each time (as anduril pointed out) <--performance issue
    2) you can set a breakpoint and see the value before the loop starts <-- troubleshooting issue which, early on, probably trumps the performance issue

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,451
    Quote Originally Posted by mike65535 View Post
    2) you can set a breakpoint and see the value before the loop starts <-- troubleshooting issue which, early on, probably trumps the performance issue
    Most debuggers will let you print the value of function calls when you're sitting at a breakpoint. In GDB, you would do
    Code:
    (gdb) p strlen(Buffer)
    $1 = 4

  5. #5
    Registered User
    Join Date
    May 2009
    Location
    Look in your attic, I am there...
    Posts
    92
    Great, thanks for the help

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. what condition in the while loop?
    By joeman in forum C++ Programming
    Replies: 3
    Last Post: 03-05-2010, 10:49 AM
  2. need while(for(loop)) to be condition
    By thestien in forum C++ Programming
    Replies: 4
    Last Post: 10-12-2006, 08:32 AM
  3. if statements using strings as the condition
    By trang in forum C Programming
    Replies: 7
    Last Post: 12-13-2003, 04:20 PM
  4. Strange if-statements execution
    By ripper079 in forum C++ Programming
    Replies: 2
    Last Post: 06-20-2003, 11:59 AM
  5. help with loop condition
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 03-23-2002, 11:18 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21