TIL 12
🐢 There are some new features in C since I learned it in 90s. One is the variable length arrays. You can now set the length of an array in runtime. This makes some use of pointers moot but Torvalds is reported to say the Linux kernel doesn’t contain any VLAs.
🐇 It may be useful though. It looks like a syntactic sugar for const pointer + malloc but implicitness is usually not a good way. It’s also using stack, it looks.
🐢 I didn’t look into the details but it may be useful in some cases. I don’t think it can replace pointer use if it uses stack though. Stack sizes are usually small and having arrays that can fill up all those is not a good approach. The other is the complex number support. It seems from the lecture that this is also a bit half baked feature.
🐇 What is the difference than using a struct with two float fields?
🐢 There are operators, +, -, * or == that support these. There is no operator overloading in C, so having a separate complex number type may be useful.
🐇 The example looks like, double complex cx = 1.0 + 3.0*I
and yes, this may be useful if you’re always using complex number in your code. But I think it’s a bit unnecessary in most of the cases. There shouldn’t be such a need for complex numbers, right?
🐢 A good complex number library will probably more than the provided type, like vectors etc. for these numbers. A dedicated library will be needed in most of the cases I believe.
🐇 The other feature added to C is that the struct members are now initialized by name or index. You can initialize an array like int a[6] = { [3] = 29, [2] = 14 };
and it will initialize only those member.
🐢 Ah, this is much more useful than complex numbers for the general case.
🐇 There is also a span syntax like int a[10] = {1, 2, [2 … 4] = 3, [5] = 30}
🐢 This is really neat.
🐇 It’s also possible to leave the initial length, so the initializer values will determine the size of the array, like int a[] = {1, 3, [30] = 55, [9090] = 1010};
will have 9091 in length.
🐢 How is this used with structs?
🐇 Instead of []
, in struct initiazers we use ., like struct Point p1 = { .x=0, .y=10 }
🐢 This is really useful and would keep much of the initialization code simpler.
🐇 There is also a way to initialize struct arrays, like
struct points pts[5] = { [0].x = 10, [0].y = 20, [3].x = 100 };
🐢 This feature is a nice addition to C, I really liked it.