Assignment Question

Started by
3 comments, last by InsaneX 20 years, 2 months ago
I was wondering if there could ever be anything wrong with doing something like this

for(int x = 0; x < count; x++)
	{
		Current->Next = new SDataEntry;
		Current = Current->Next;
		TotalNodes++;
	}
My question is about the assignment Current to equal Current->Next. Could that cause a problem?
Advertisement
No problems with the assignment, no.

Using std::list is generally preferable to rolling your own linked-list.

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” — Brian W. Kernighan (C programming language co-inventor)
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Remember that the order of operator precedence is very well defined in C++. Here''s a list if you don''t have one handy in a book or something.

So what happens with your statement "Current = Current->Next; " is that all your operators are considered. That line only has two: = and -> . If you check the chart, -> is way way higher than = , thus it executes first. So Current->Next is evaluated, and is effectively replaced by its result, which is the value of the pointer Next . Then, all the operators are considered again. This time there is only one left, = , so it is evaluated. That which is on the left becomes equal to that on the right (which is currently the pointer value from Next ), and then it is replaced by that value. Now there are no operators, and just a simple value, so the evaluation of the entire line is done.

Hopefully stepping through the process of what occurs might help understand why that is perfectly valid, and doesn''t lead to any wierd effects. So always remember (assuming nothing fancy likes threads are involved) that lines are executed one single operation at a time, and the order in which those operations are executed are almost always very well defined. Most of the time, an order-of-precedence table will be all you need to figure out how a line is evaluated.
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
The two problems I see are the series of dangling pointers and the absolutely horrible indentation of brackets.
quote:Original post by Anonymous Poster
....the absolutely horrible indentation of brackets.


Prude

This topic is closed to new replies.

Advertisement