Search code examples
coperators

Studying operators in C


I was studying the following piece of code and tried to write on paper the values that i and j receive at each step but I don't understand why at the 4th step, j's value decreses from 3 to 2 as there is no decrement operator (as far as I understand it):

#include<stdio.h>

int main() {

  int i, j, n;

  int v[] = {
    -7,
    29,
    76,
    8
  };

  n = sizeof(v) / sizeof(int);

  for (i = 0, j = 1; n > 1 && i < n;
    (v[i] > v[j]) && (v[i] = v[i] + v[j] - (v[j] = v[i])), i++, j = j < n - 1 ? --i, j + 1 : i + 1) 
       printf("i=%d j=%d \n", i, j);

  for (i = 0; i < n; i++) printf("%d\t", v[i]);

  printf("\n");

  return 0;

}
Output: 
i=0 j=1 
i=0 j=2 
i=0 j=3
i=1 j=2
i=1 j=3
i=2 j=3
i=3 j=4
i=3 j=5
i=3 j=6
-7      8       29

Tried to understand how i and j receive their value.


Solution

  • I hope this will help:

    1. The first "part" of for statement sets the initial values of i and j (0 and 1 respectively).

    2. The third "part" of for statement is responsible (in your code sample) for all other changes of i and j values. This part is a comma expression (with three subexpressions), that is evaluated from left to right. These subexpressions are (in order of evaluation):

       (v[i] > v[j]) && (v[i] = v[i] + v[j] - (v[j] = v[i]))
      

    That means: If (v[i] > v[j]), then give v[j] the previous value of v[i] [part: (v[j] = v[i])] and v[i] the value of v[j] (part: v[i] = v[i] + v[j] - (v[j] = v[i]), note that v[j] = v[i] evaluates to v[i]). In other words: If v[i] is greater than v[j], then swap the values of v[i] and v[j].

         i++
    

    The simplest part: Increment i value by one.

         j = j < n - 1 ? --i, j + 1 : i + 1
    

    Here is used the tertiary operator (?:). If (j < n - 1) is true, then "--i, j+1" (another comma expression) is evaluated (from left to right) and its value (the value of last/right part, ie: j+1) is assigned to j. In other words: the value of i is decremented by one and j is incremented by one, if j is less than n-1. If j is not less than n-1, then the last part of tertiary operator, i+1, is assigned to j.

    By the way: I think that the last line of your output must be: "-7 8 29 76" and not "-7 8 29". So, this piece of code sorts v[] array.