user2131316
user2131316

Reputation: 3277

what does the following code do in C?

I saw the following code from somewhere:

while(*i++ = *j++)
{
}

but what is this code doing? what is the meaning of it?

Upvotes: 1

Views: 188

Answers (6)

monnoroch
monnoroch

Reputation: 390

Most likely, if i and j are char*, then it copyes null-terminated string j into memory that starts at i. You might wanna keep in mind that i and j itself changes (i += strlen(j)) so code above also breaks the pointers to a strings.

Upvotes: 3

noufal
noufal

Reputation: 970

It primarily depends on what i and j are. One case can as be follows.

Assume that i and j are two pointers to a character string, then the value of i and j will get simultaneously increased, and assign the value of *j as *i, whenever the value of j becomes 0 ie, \0 the loop will exit after assigning that 0 to *i.

Obviously this can be used to copy the content of j to i.

Upvotes: 0

Umer Farooq
Umer Farooq

Reputation: 7486

*j++ derefrences the pointer, increments its value.

*i++ = *j++ assigns the old value of *j to *i, then *i++ increments this value and saves it for use the next time

while(*i++ = *j++)

is executed.


If i and j are char[], then

while(*i++ = *j++)

is copying characters from j[] to i[] until NULL character is reached.

Upvotes: 1

Lundin
Lundin

Reputation: 213842

In addition to the other answers, while(*i++ = *j++){} is a less readable, more compact and more dangerous way of writing

*i = *j;

while(*i != 0)
{
  i++;
  j++;
  *i = *j;
}

The two cases will generate exactly the same machine code.

Upvotes: 1

Neil Kirk
Neil Kirk

Reputation: 21773

It copies the data pointed to by j, to the array pointed to by i, and continues until a value of 0 has been copied. It is perhaps used to copy a null-terminated string. To be even more clever, you can use

while(*i++ = *j++);

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249153

It copies elements from an array (or a pointer to an array) called j to one called i. It does this until it finds a value (from j) which is equivalent to zero.

This is a common idiom for copying C-style, null-terminated strings; it could also be used to copy an array of integers terminated by a sentinel zero.

In case the size of j can be known in advance, it might be better to use memcpy(). And in case the size of j cannot be known in advance, it is likely the code is unsafe, because the proper size to allocate for i cannot be known either.

Upvotes: 4

Related Questions