"Simplify" to one line
just doing my Homeworks and discovered this piece
A[j]=A[j-1];
j--;
is there a way to simplify this to one line? edit one statement?
I've tried
A[j--]=A[j];
but it doesn't seem to work 开发者_如何学运维well.
the code is from an InsertSort algorithm
edit this question is not required to do my homework, i am just curious
From the standard:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
That is, A[j] = A[--j];
will result in undefined behavior. Don't do it. A[j]=A[j-1]; j--;
is perfectly clear, concise, and satisfactory.
If the goal is just to eliminate the ;
in the middle so you can use this in a macro context or as a single statement without braces, try using the comma operator:
A[j]=A[j-1], j--;
or if you want the assigned value as the result of the expression:
j--, A[j+1]=A[j];
Both should generate identical code on a decent compiler if the result of the expression is not used.
As others have said, any attempt to do this without the comma operator will result in undefined behavior due to sequence point issues. If you don't have a good reason for condensing code like this, I would recommend not even doing it. Unless you're very experienced with C, you're almost sure to mess it up and introduce subtle bugs (some of which may manifest not with your current compiler, but in future versions of it, creating hell for whoever gets stuck debugging the code).
There is actually a way
A[j+1]=A[--j];
is works well in VC but causes UB on g++
精彩评论