Completing C code with D style
forkit
forkit at gmail.com
Thu Nov 11 22:30:12 UTC 2021
On Tuesday, 2 November 2021 at 23:45:39 UTC, pascal111 wrote:
> Next code originally was a classic C code I've written, it's
> pure vertical thinking, now, I converted it successfully to D
> code, but I think I made no much changes to make it has more
> horizontal thinking style that it seems D programmers care in
> horizontal thinking style. Is there any additions I can make in
> the code to make it suitable with D style or it's fine?
>
ok.. for a more on topic response..
First: Please name your variables sensibly:
char negativity, even; // grrr!!!
char answer1, answer2; // makes so much more sense
Second: You need to use D-style syntax in your array
declaration
int numbers[10] = [-3, 14, 47, -49, -30, 15, 4, -82, 99,
26]; // C style
int[10] numbers = [-3, 14, 47, -49, -30, 15, 4, -82, 99,
26]; // D style
Third: you're asking for trouble in your for loop declaration.
for(int i = 0; i < 10; ++i) // grrr!! What if you counted up
your elements incorrectly?
for(int i = 0; i < sizeof(numbers) / sizeof(int); ++i) // is
so much safer - in C style
for(int i = 0; i < numbers.length; ++i) // is so much safer
- in D style
Finally, D is multi paradigm. That's probably the first (and most
important) thing you should know about D. Yes, you can write C
style easy, and in many cases, that's just fine. You can also
write in other styles.
But sometimes it is worthwhile rewriting code differently, to see
what advantages, if any, comes about. D is a language where you
can actually do just that. Above is a good (although very basic)
example - i.e. change the way you define a for loop, so that it's
safer, simpler, and more maintainable.
Also, use of lambdas, UCFS, etc.. (which is probably what you
meant by 'horizontal' code), if used sensibly, can remarkably
reduce and simplify code, as well as contributing to the
maintainability of that code.
Thankfully, D is multiparadigm (which is its best and worst
feature), and so it lets you can experiment with different
styles. Try doing this in C, Go, Rust...
More information about the Digitalmars-d-learn
mailing list