4 ms·
The second version seems more elegant but will scare non-C people away with all those pointers ;-) What I do not understand is why one should use an "IntList"
by m4lvin 6y ago
The second version seems more elegant but will scare non-C people away with all those pointers ;-)
What I do not understand is why one should use an "IntList" struct in the first place? As the explanation of the second method suggests, a List is the same thing as a pointer to its first element, so why not do this?:
typedef struct IntListItem* IntList;
Also, could it be that both methods fail terribly (infinite loops?) when they are given wrong input such as elements not in the list at all?
- MauranKilom 6y ago> Also, could it be that both methods fail terribly (infinite loops?) when they are given wrong input such as elements not in the list at all? You could just say "has undefined behavior unless target is an element of the list". Whatever your choice though - this is slide code. It should be obvious that it's not production ready.
- Animats 6y agoUm, yes. That jumped out at me. If there's a no-find, the code will de-reference null and crash. That's just not acceptable. Try to write that in Rust, using Some(ref) for the forward link, and the compiler will force you to test for None and detect the end of the list. This is pre-1990s programming style. I've seen such code in assembly programs. Because I was reading crash dumps where it failed.
- souprock 6y agoIt's 100% acceptable. You should not remove something from a list unless you know it is there. Since you won't attempt to remove something that doesn't exist, any code to check for that situation is an unjustified performance loss. (separate code exists for searching a list) This... is not Python. C programmers, particularly kernel developers, have that style even in 2020.
- Animats 6y agoI hope not. Kernel programmers need to be paranoid. This is a classic idea for doubly linked lists. The empty list has the head element linked to itself in both directions. Buffer rings are sometimes organized that way. The cases for doubly linked lists are messier. Bear in mind that in modern CPUs, branches to nearby code are almost free, but indirection to far memory is expensive.
- kevin_thibedeau 6y agoTypedefing pointers was done so Pascal programmers didn't have to be scared by C syntax. This is why Microsoft went overboard with this practice. It unfortunately hides the language for no real benefit.