-4
int main() 
{
    struct data{
        int a;
        int b;
    }y[4] = {1,10,3,30,2,20,4,40};

    struct data *x = y;
    int i;

    for(i = 0; i < 4; i++)
    {
         x->a = x->b, ++x++ ->b;
         printf("%d%d\t", y[i].a, y[i].b);
    }


    return 0;
}

How does this code work?

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • 1
    Don't change the question after getting answers and comments. And don't make the question to broad. `->` is the structure reference operator ( Google it for more information on that ) and `= { ... }` initializes all the elements of the array with the values in the initializer list. Play with it for a while and you'll get the hang of it :-) – Spikatrix Aug 22 '15 at 16:03
  • No professional or enthusiast programmer would care because all such code is garbage, as is this question. – Martin James Aug 22 '15 at 17:37
  • I'm voting to close this question as off-topic because the code in the question is execrable and is of zero, or negative, use to future visitors. – Martin James Aug 22 '15 at 17:39

3 Answers3

4

The statement

x->a = x->b, ++x++ ->b;  //note the comma operator after x->a = x->b

is equivalent to

x->a = x->b;     // Assign member `a` to first member of element of array y 
++( (x++) ->b);  // Fetch the member b of element of array y and then increment 
                 // it by 1. Increment `x` by 1 after `b` is fetched.
haccks
  • 104,019
  • 25
  • 176
  • 264
4

The ++x++ is well defined in this context:

++x++->b

that is equivalent to:

++((x++)->b)

This means that two different x and x->b lvalues are incremented, not single one (which would be an UB). You may rewrite it into two statements:

++(x->b);
x++;

The full expression statement:

x->a = x->b, ++x++ ->b;

is valid, since there is sequence point (because of comma operator) after x->a = x->b is evaluated (there were no side effects in this one, so result of this subexpression was discarded).

Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137
1

This expression

x->a = x->b, ++x++ ->b;

uses the comma operator and in fact for clarity can be split in two statements

x->a = x->b;
++x++ ->b;

The second subexpression can be imagine the following way

struct data *temp = x;
++x;
++temp->b;

that is it increases data member b of the structure pointed to by pointer x and increases the pointer itself.

So data member b of the current structure (object of type struct data) is increased and the pointer will point to the next structure.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335