wat does this function do?

This is a discussion on wat does this function do? within the C++ Programming forums, part of the General Programming Boards category; Code: int mystery2(const char *s) { int x; for (x = 0; *s!='

Thread: wat does this function do?

'; s++) ++x; return x; } i dont ...

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    13

    wat does this function do?

    Code:
    int mystery2(const char *s)
    {
       int x;
       
       for (x = 0; *s!='\0'; s++)
           ++x;
    
    return x;
    }

    i dont understand wats *s! = '\0' and ++x; for

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,535
    One compares something with zero, and the other increments a value.

    You could just try calling it with a few strings, and observing the output you get.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Feb 2005
    Posts
    13
    but why not use s != 0 instead using s != '\0'

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    They're effectively the same thing. However, the character null is in fact '\0'. See the single quotes? That means it's a single character. This single character here is what we call the null character.

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    8
    The function calculates the length of the string that s points to. *s means the current character in the string and '\0' is the null character with which all strings end. So the function checks for the end of the string and increments x and s by one. In the end, x holds the length of the string.

  6. #6
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Nice hint.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 01:28 PM
  5. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 01:53 AM

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