What does this line of code does in C programming?

Viewed 92

code :-

pu->queue[ pu->rear = (pu->rear + 1) % pu->size ] = x;

I know the workings of the queue but i'm just confused about the assigning variables inside the index value of the arrays. Is this a good practice? Does that work? I can't compile because i don't have the full code.

Edit :- Solved. but that code does compile. now that i have access to the code itself, it compiles without warnings.

3 Answers

It's short for

pu->rear = (pu->rear + 1) % pu->size;
pu->queue[pu->rear]

An expression returns a value, and can thus be used within a larger expression. A statement doesn't return a value, so it can't be used in an expression (without a do { }-style construct). An expression can be usually be used as statement (where its returned value is discarded).

In some languages, assignments are statements. In others, assignments are expressions. In C, assignments are expressions. They return the value that was stored. As such,

pu->queue[ pu->rear = (pu->rear + 1) % pu->size ]

is short for

pu->rear = (pu->rear + 1) % pu->size;
pu->queue[pu->rear]

The code appears to be implementing a circular buffer.

I'm going to tackle this part of the question:

Is this a good practice?

No, for these reasons:

  • It's hard to understand at a glance, because you have three different things happening - two assignments and a subscript operation;
  • This style can make code hard to analyze in a debugger - there's no good way to set a breakpoint to verify the computation of the new value of pu->rear before using it to subscript into the array.

This specific instance isn't too bad, but it's not a good habit to get into.

It seems that the code deals with a circular queue. This expression

pu-rear = (pu->rear + 1) % pu->size

determines the index pu-rear in the array pu->queue where a new data will be written.

For example if you have an array declared like

T a[2];

and the initial index i equal to -1 then the first element will be written at the position ( i + 1 ) % 2 that is at the position 0.

The next element when i is equal to 0 (after the previous operation) will be written at the position ( i + 1 ) % 2 that is at the position 1.

The third element when i is equal to 1 will be written again at the position 0

( i + 1 ) % 2 == ( 1 + 1 ) % 2 == 0

That is when the end of the array is reached new elements are added at the array beginning anew.

To make it more clear consider the following demonstrative program.

#include <stdio.h>

int main(void) 
{
    enum { N = 3 };
    int a[N];
    int i = -1;
    
    for ( int value = 0; value < 10; ++value )
    {
        a[ i = ( i + 1 ) % N ] = value;
        
        printf( "i = %d, a[%d] = %d\n", i, i, a[i] );
    }
    
    return 0;
}

Its output is

i = 0, a[0] = 0
i = 1, a[1] = 1
i = 2, a[2] = 2
i = 0, a[0] = 3
i = 1, a[1] = 4
i = 2, a[2] = 5
i = 0, a[0] = 6
i = 1, a[1] = 7
i = 2, a[2] = 8
i = 0, a[0] = 9
Related