Jump to content
Sign in to follow this  
Shree

A (Not So) Common 'c' Question About Pointers.

Recommended Posts

Hello All,

Came across the code below. Could not figure out exactly what it does. Can somebody please tell me what exactly the code does. especially, the "for" is used in a different way it seems. Just confused about it :(.

 

char * Somevalue(char * X, const char * Y)
{
 char * d ;
 d = X;
 for(;*X++ = *Y++ 
;
 return d;
}

 

Thanks & Regards

Shree

Edited by Shree

Share this post


Link to post
Share on other sites

This looks like string copy to me.

 

The for loop says copy the character pointed to by Y to the location pointed to by X. Advance the source pointer (Y) after the character is read and advance the destination pointer (X) after the character is written. Keep doing this while the character transfered is not zero. Once a zero is copied (the string terminator), break out of the loop. When the loop is finished return a pointer to the begining of the string copied (original value of X);

 

Note that for has spaces for statements. The first space is optional and says what to do before the loop is started, the 2nd space is not optional and requires a statement which when evaluated to 0 will break out of the loop. The 3rd space is for an optional statement to be performed at the end of the loop.

 

So the for could have been replaced with while(*X++ = *Y++);

 

 

for(a,b,c){

d

}

 

is the same as

 

a

while( b ){

d

c

}

the for loop is just a little more compact but was not really needed for the language.

 

I hope this helps.

Ted.

 

P.S. if you changed the *Y++ to *++Y the first character will be skipped since the pointer is advanced before the character is read.

Edited by trossin

Share this post


Link to post
Share on other sites

Hi

 

I think its the other way around.

The "for" construct is the most complete and versatile of all.

The "while", "do-while" and "repeat-until" contructs are the particular cases, and all can be replaced by the "for".

 

In complex expressions like "*X++ = *Y++", if in doubt, add parentheses by the rules of the 'C' operators precedence and things become more readable.

You can easily find a precedence chart online. This is one of them http://www.swansontec.com/sopc.html

 

 

Best regards

Jorge

Edited by JorgeF

Share this post


Link to post
Share on other sites

Join the conversation

You are posting as a guest. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...