How come this works?

This is a discussion on How come this works? within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> #include <string.h> int main(void) { int i; char str1[] = "abcdefghijklm..."; char str2[100]; for (i = 0; ...

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    204

    How come this works?

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        int i;
        char str1[] = "abcdefghijklm...";
        char str2[100];
    
        for (i = 0; str1[i]; i++)
            str2[i] = str1[i];
    
        str2[i] = '\0';
    
        printf("%s\n", str2);
    
        return 0;
    }

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Because when str[i] hits a null ('\0', 0x00, %00, \000, 0) than it will break the loop, because it is 0. The middle statement is the check statement, like the portion inside a while(), execution occurs while it is non-zero.

  3. #3
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,528
    Yep, to add some code to Tonto's explanation:
    Code:
    for (i = 0; str1[i]; i++)
    could have been written:

    Code:
      for (i = 0; str1[i] != '\0'; i++)
    That is basically what is happening, whether it is written explicitly, or implicitly. I would say the latter example is clearer though.

    ~/
    Last edited by kermit; 08-19-2005 at 04:46 PM.

  4. #4
    cwr
    cwr is offline
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    868
    Though kermit's latter example with the explicit compare to '\0' is clearer, having an implicit test for the '\0' character is a popular idiom in C and should be easily recognisable. The code could also be written as:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        int i = 0;
        char str1[] = "abcdefghijklm...";
        char str2[100];
    
        while (str2[i] = str1[i++]);
    
        printf("%s\n", str2);
    
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can anybody show me why this works??
    By tzuch in forum C Programming
    Replies: 2
    Last Post: 03-29-2008, 09:03 AM
  2. fprintf works in one function but not in the other.
    By smegly in forum C Programming
    Replies: 11
    Last Post: 05-25-2004, 03:30 PM
  3. Works only part of the time?
    By scr0llwheel in forum C++ Programming
    Replies: 1
    Last Post: 01-07-2003, 07:34 PM
  4. Programs works one way, not another. VC++ 6.0 help.
    By Cheeze-It in forum Windows Programming
    Replies: 4
    Last Post: 12-10-2002, 09:29 PM
  5. it never works...
    By Ryce in forum Game Programming
    Replies: 5
    Last Post: 08-30-2001, 07:31 PM

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