This works (notice the str+1 in the last line):


Code:
char *strchr( char*str, char ch)
{
   if (*str == '\0')
   return NULL;

   if (*str == ch)
   return str;
   
   strchr (str+1, ch);
   
}


But this doesn't:


Code:
char *strchr( char*str, char ch)
{
   if (*str == '\0')
   return NULL;

   if (*str == ch)
   return str;
   
   strchr (str++, ch);
   
}


Is it because using str++ causes str to be used throughout the function and only incremented in the end, after the strchr(str++,ch) line, causing the non incremented str to be sent to all functions and causing an infinite loop?
There are two forms of the ++ operator: prefix, and postfix. They return different values. The postfix version updates the variable but returns the old value as the value of the expression. The prefix version updates the variable and returns the new value as the value of the expression.

This code:

Code:

void plusplusfun(){
int a = 0;
int b;
int c;

b = a++;
c = ++a;

printf("a = %d; b = %d; c = %d\n",a,b,c);
}

will print out:
Quote:

a = 2; b = 0; c = 2;
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement