The well-documented comma operator (K & R, etc.) is presented in a fairly large algorithmic code and is often a surprise to many programmers who have not seen this before. It is often used to simplify some loop designs:
#define kITERATIONS_MAX 10 int i=0,j=0,array[kITERATIONS_MAX],outArray[kITERATIONS_MAX],temp=0; for (i=0,j=kITERATIONS_MAX-1; i < kITERATIONS_MAX; i++,j--) { temp = array[i]*array[j]; outArray[i]=temp; }
The above code will multiply the elements of the array from 0 to 9 from 9 to 0, avoiding nested loops.
When using the comma operator, both the first and second expressions are evaluated. The result of the first expression is ignored and the result of the second expression is returned.
mikecsh
source share