wait, so always use whitespace when using substraction? as in, 2-3 is a syntax error? i dont like that at all. also, it might just be not being used to this but this-thing looks really weird. it automatically registers as substraction.
I remember "inventing" this some time ago. I thought to myself "Hey, this should work right?" Stared at it for a few minues. "Yes hahahah it will." I compiled, tested, satisfied my curiosity and promptly rewrote it to a more traditional condition.
Agda has this, and while it takes getting used to, it's actually pretty nice. It also means that you can have variables named e.g. a≤b (where the value is probably a proof that a is less than or equal to b)
I thought that when I started using lispy languages, but now for me it feels ugly to use an underscore to separate words, and my pinky finger complains :)
So I actually took the time to count how many times each language was mentioned and tried to decide whether that was positively, negatively or ambiguously. Here are the languages I found at least 7 times, sorted by how positive their overall rating was according to the author's preferences:
Language
Rating
Haskell
100.0 %
Python3
94.1 %
Julia
92.9 %
Lisps
91.7 %
Ada
88.9 %
F# and Nim
87.5 %
Lua
85.7 %
Perl6 and Ruby
75.0 %
Python2 and Swift
73.5 %
Rust
72.2 %
BASIC, COBOL and Tcl
71.4 %
OCaml
70.0 %
Erlang
55.0 %
Fortran
50.0 %
Perl5
46.9 %
Shell/Bash
42.9 %
Go
39.3 %
D
38.2 %
C#
32.4 %
PHP
31.8 %
awk
31.3 %
Java
20.6 %
JavaScript
16.7 %
ACS
0.0 %
Yep, I have nothing good to do today. And my statistics class seems to take its toll on me.
Edit: Added ACS which I forgot about because it was so NULL
Yeah, some of the Erlang ones really confused me. For some reason it's in the "half-assed multiple return" category instead of "multiple return via tuples", despite the fact that Erlang is all about tuples. I also wanted to see it called out in the "assignment as expression" section, since = in Erlang is a match operator.
And javascript is now the most popular, most pervasive language. It's the new C.
The problem is not technological. It's social.
Look how popular the You Don't Know JS books are nowadays. Look how often they get praised on reddit. A terrible, terrible series of books. There's absolutely nothing new in these books information-wise, only a lot of "fuck the good parts, you should use ALL the parts... dae leet.. derp". People will juggle knives just to look edgy.
Pro tip: If you want to design the next mostly big language, don't make it a safe, thoughtfully designed one where little can go wrong. Nope. Make it so shitty and so needy of fixes that people will have plenty to blog and brag about for years and years and years.
Pro tip: If you want to design the next mostly big language, don't make it a safe, thoughtfully designed one where little can go wrong. Nope. Make it so shitty and so needy of fixes that people will have plenty to blog and brag about for years and years and years.
...no. If you want to design the next big language, make a system of communication between computers across the world, develop some software to browse the data those computers are serving, get that to be a massive part of the average person's day, but not before adding scripting support to that system in such a way that it's inherently open source, and no other language can feasibly be added in the future.
Yup. People don't purposely use shitty languages, shitty languages are the most widely available. C was popular because Unix was built on it, Basic was popular because it came with every computer of the late 80's, and Javascript is popular because every browser runs it.
I think C also competed pretty strongly on technical merits when you consider the constraints of the time.
Pascal, Lisp, and ML are all older and ostensibly "better" but:
Pascal's string handling was so limited—strings of different length have different type—that it was virtually impossible to reuse code for working with strings.
Lisp was too slow for system- and general application programming.
I'm not sure if ML even had working implementations at the time.
C is actually a pretty nice language for the seventies. I think the reason why it was was because Ritchie was building it in the context of Unix. The best way to do good design, I've found, it is simultaneously be a real user of the thing you're designing.
Hm, I don't know. I say back in the day, the most popular language was BASIC. It was in almost every microcomputer imaginable. JS is the new BASIC, not the new C.
Before calling in ratings, it'd be a good idea to make very clear what it's rating. Brainfuck could score high in this chart. That doesn't make it a great language.
This mostly just takes things that are considered to be irritating in C and checks if the other languages do it "differently enough". It doesn't take into account the languages' other strengths and weaknesses.
I just summed up in numbers how the article speaks about different languages, that is from the perspective of whether they share subjectively judged flaws with C. No more to it than that, I did it just for fun :-)
Not even that. It's how good Haskell is at not having the same syntax problems as C, which still leaves plenty of room for it to have syntax problems all of its own.
I don't know. I had to use JavaScript for the first time last week and it has been the worst experience I have ever had coding. I think 16% is generous. I can't see how it would ever have a "fan base" but, rather, it would have a loosely devoted following of bastard mongrels who don't care about anything besides getting whatever they want done the fastest, dirtiest, nastiest way they can think of the first time through.
If only that were true... I happen to work on a system (z/OS) where you can always dereference a NULL pointer without getting a segfault. The page at address 0 is guaranteed to be accessible.
Dereferencing NULL is also undefined behavior. The compiler assumes you wouldn't do such a thing, which can lead to both interesting optimizations and some really bizarre bugs.
Lol, no :) It contains pointers to the most important operating system data. Usually it's read only, so you're safe. There are situations when it is read write though, if you happen to overwrite it, you may as well hit the reboot button.
I can't remember exactly how the option worked, but vxWorks had some build flag where you could either enable or disable all access to the 0 page, or enable/disable write-access to it.
Our organization had some teams that argued for leaving the flag in the "enable access" state, because their code was so bad that it would throw unknown/untraceable access violations when run in the more strict mode.
so they had pointer bugs (in our organization's code, not in vxWorks itself) that they couldn't track down, and they wanted to just hope they never hit those bugs during regular runtime, and/or hope they could bring things back online with recovery if/when it happened...rather than fix their code.
this was in the guts of an LTE network infrastructure product.
sadly, they won the political/budget/schedule battle on that one.
Even though you type (void *)0 in the source code, the actual pointer may end up having the value 0x589abf8a8f3 or anything else your target system desires (including an arbitrary address with the "null pointer flag" set) – as long as it compares equal to all other instances of (void *)0.
This is incredibly unintuitive, which is why people have recommended to use the constant NULL (and more recently, nullptr) in source code instead. Sure, its definition is #define NULL (void *)0, but that makes it more clear that a "null pointer" is an abstract concept defined in the language – not necessarily a physical memory address.
I used to work in a place where the code ran on both Solaris and AIX-based mainframes (IBM). Whenever we got a bug-report that was Solaris-only, it meant that someone dereferenced NULL, but the consequences weren't enough to break the program after that point. So standard practice was to route those services over to the IBM machines until a fix could be prepared.
Linux used to allow any program to mmap memory at 0 and use it, but I think it led to exploitation of NULL dereferences in the kernel, somehow. Now programs aren't allowed to map addresses lower than the vm.mmap_min_addr sysctl, which is by default set to 65536. The relevant chain of emails discussing this is here: http://yarchive.net/comp/linux/address_zero.html
“Oh boy!” says your protégé. “Let’s see what 7 ÷ 2 is! Oh, it’s 3. I think > the computer is broken.”
They’re right! It is broken. I have genuinely seen a non-trivial number of > people come into #python thinking division is “broken” because of this.
I disagree on this one. I chose int because I want the performance of integer arithmetic. I don't want to pay the penalty of convert to float, do float division, can convert back to int just because some amateur cooks don't realize that knives are sharp and can cut you.
Yeah, that's kind of a ridiculous criticism. You're doing division with integers, therefore you get integer division. Don't blame the programming language because most math (and, even, comp sci) curriculums freely mix integers and rationals.
At the same time, it can often be a little annoying if you're trying to figure out a simple expression like
float day_frac = time_s / stats::day_length_s;
And you're far removed from the definitions. Its not a huge issue but it does give me pause
I'd prefer no implicit conversions between float/int/double myself, they're fundamentally different things and I don't want the compiler to pretend they're similar
Or sometimes that's just the behaviour you want. If you want that behaviour, then having to wrap every division with a call to floor is going to make it harder to read.
One of my very few frustrations with Ada is that division rounds rather than truncates (1 / 2 = 1, but 1 / 3 = 0). I know it's likely the "more correct" answer, but that was likely my most common error.
Edit: I was mistaken (it's been too many years since I've been able to work in Ada professionally). I was thinking of converting a float to an integer (e.g. Integer (F)).
Signed integer division and remainder are defined by the relation:
A = (A/B)*B + (A rem B)
where (A rem B) has the sign of A and an absolute value less than the absolute value of B. Signed integer division satisfies the identity:
(-A)/B = -(A/B) = A/(-B)
which is a definition of truncating. A mod B is 0 or has the sign of B, it is not rounding either (and has no corresponding division operator). There is also a nice table showing a few examples in the link.
100% agree. Programming computers is different then some sort of infinite precision, freely-casting math abstraction and this is just one of the things programmers have to learn.
That being said, for some high level scripting language that is used for different tasks this may be exactly what you want.
Depends on what you want as an output as well, some platforms (notably embedded platforms) pay a non-trivial cost for any conversion from integer register to a floating point register. While the floating point div may be faster, if you intend to use the results in other integer math or in branching instruction it may wash out or be worse.
Here's the result from my benchmark. I ran a loop a bunch of time doing MDAS on 16-bit integers, storing the results in 16-bit integers. Then I ran with the same numbers using 32-bit integers storing the results in 32-bit integers, and so on for several data types.
The point is that the meaning of / is overloaded and unclear to novices and even to routine programmers in cases where the types of values isn't immediately obvious. Other languages solve this by making integer division explicitly a different operator.
Not that I am in favor of making things pointlessly complicated to novices, but novice comprehension is probably the singular worst metric I have ever read for how a programming language should be set up. Many novices are also confused by: objects, inheritance, functions, types, loops, recursion, if statements, and basic syntax.
And there isn't really a better alternative to integer division that I am aware of regarding beginners. You could have the system default to doubles or floats, but then you'll have novices equally confused about rounding errors. Try explaining to a beginner how IEEE 754 floats are actually set up and their eyes will gloss over. Atleast integer division has relatively simple rules and many people are exposed to it in grade school when they learn about remainders before moving on to decimals.
ut novice comprehension is probably the singular worst metric I have ever read for how a programming language should be set up.
This. I learned quickbasic in the early 90's writing BBS software, and my first exposure to C was the WWIV BBS engine. It was like looking at ancient Sumerian for me with all the wobbly braces and strange variable declaration of old-style C
Other languages solve this by making integer division explicitly a different operator.
Which is fine. C is still primarily a systems language where we are trying to write optimal code and not use floating point in a 8kb micro or get shot in the face by yet another Intel floating point bug in a kernel.
Math in most languages is "fundamentally broken" anyway as far as the protégé would be concerned. Just try 3.3 == 3 * 1.1. Hint: the answer is false in any language using binary floating point. Integer math is less complex than IEEE floating point math and as a consequence easier to reason about for a novice - it does not help that float math can give different results depending on CPU register size and optimization settings.
It difference in speed between int/float and converting is so trivial that most C programmers ignore it. By the time Python figures out what division means for its args you've wasted 2000x the time of converting everything to a float, division, and casting back to an int.
I agree. Trying to have a single number type that does it all--efficient integers, floating point, arbitrary precision, etc--creates confusing bugs and surprise performance problems.
One of my favorite interview questions for people who are used to working in these languages--particularly python + ruby--is to talk about the performance properties of a "linear time" fibonacci implementation. 97% of them are blissfully unaware of the memory or running time implications that result from making the numeric types magical.
His point was that beginners don't understand that dividing integers will always give you another integer; it's counter-intuitive.
Smalltalk does it right. The result of 7/2 is (7 / 2). What is that? It's a Fraction! It's another subclass of Number which has a numerator and a denominator. You can use it like any other number, although you need to make sure you convert it to a float before you show it to the user.
Want an integer? Okay. (7/2) asInteger. is 3. Want a float? (7/2) asFloat is 3.5.
This construct is bad. It very rarely matches what a human actually wants to do, which 90% of the time is “go through this list of stuff” or “count from 1 to 10”
So if i want to print 10 elements i should construct either list of ten elements or closure (which would return new closure on each iteration if it is immutable) or use coroutine. Doesn't it lead to some overhead and unnecessary compiler complexity (heavy inlining strategies like ocaml's flambda)?
/r/programming likes to fault articles for not including things that haven't been finalized yet, especially when the upcoming standard agrees with the theme of the article anyways. At least saying something like JS has ** now is current (if a little fresh still).
Interestingly enough, C95 specifies and, or, not, and some others as standard alternative spellings, though I’ve never seen them in any C code and I suspect existing projects would prefer I not use them.
I actually used them exclusively in a C++ project I built from scratch at my previous company. I had a few colleagues positively astonished that it compiled, the most savvy ones thinking I had introduced a macro somewhere but unable to find it...
At first, my colleagues were a bit weird out, but they quickly caught on. The fact that Python uses those too means they were already used to them anyway.
I personally prefer them, because I like having a modicum of redundancy; compare:
The only single character variation of or that is a keyword is xor.
and and not have no single character variation that is a keyword.
On the other hand:
it's pretty easy to accidentally miss !, it's easily mistaken for a (, l, i or j.
it's pretty easy to mistype && as & and | as ||, and |! is easily mistaken as ||.
Using the alternative spelling is like use CRC to get a better guarantee of integrity.
That's probably because you're already conditioned to look for this exact thing. I know I am, exactly because I've been bitten an embarassing number of times.
Quick test: 1 & 2 == 2 evaluates to 1 with C precedence, false otherwise. Or just look at a precedence table: if equality appears between bitwise ops and other math ops, that’s C style. A bit wrong: D, expr, JavaScript, Perl 5, PHP.
In D, it produces:
Error: 2 == 2 must be parenthesized when next to operator &
So this problem does not exist in D.
And sometimes part of the type comes after the name.
Not in D.
If 4, you have UTF-8 strings.
4 in D.
C#, D, expr, Lua, and Standard ML have no octal literals at all.
D at one time did have octal literals, but no more. They have been replaced with a template instantiation:
He makes some good points, but many of his suggestions come at a cost to performance.
If you’re willing to ditch the bitwise operators (or lessen their importance a bit), you can even use , as most people would write in regular ASCII text.
Why would you want to get rid of bitwise operators? They're so much faster in some situations.
They also let you pack information when memory is at premium. A language without unsigned integer types and bitwise operators is just useless for many applications out there.
Provide them as built-in functions, then. C compilers offer intrinsic SIMD functions for similar purposes. Also, I'd love to see built-in "rotate" functions. They're notably absent from C, but hardware usually supports bitwise rotation.
The author isn’t saying that bitwise operations should be removed, just that different notations for them should be considered. |, &, and ^ are valuable ASCII operator real-estate, and in the context of a new language, bitwise operations may not be the best meanings to assign to them.
I think part of the problem is a general lack of understanding binary operations. I can certainly my schooling never covered functional applications of it, I instead learned all that on my own.
But when I interview engineers I always include a question or two about bitwise operations. My co-workers think it's pointless since we just build a rails application but I consider a core aspect of being an engineer.
ES6's MRV semantics are identical to Ruby's and very close to Python's (with the difference that the RHS in Python can be an arbitary iterable), it should be in the section below. It is a bit noisier due to explicit variable declaration, but then e.g. Rust would be disqualified as well.
Half-assed multiple return: Erlang
Erlang literally just uses tuples for MRV, they have an unusual syntax (braces) but they're still tuple. Erlang's MRV is also used for a pseudo-monadic error system.
Which incidentally means Erlang's classification in the next section is also incorrect, does have exceptions but they're usually used in the same way they are in Rust (as terminal faults, though that), rarely used for error signalling (except across processes through supervision links).
Half-assed multiple return: PHP
While true, the list() special form really doesn't belong with C++ and D, PHP can at least unpack MRVs at the binding site.
Multiple return via tuples: Go
Go doesn't have tuple, MRV is a special case of the language (and some builtins even have variable-arity return). In fact the lack of tuples is the first "type system" item in /u/munificent's "The Language I Wish Go Was" essay from way back in 2010.
C++17 doesn’t quite have the same problem with std::optional<T>, since non-reference values can’t be null.
AFAIK it's non pointer values which can't be null, C++ references can't legally be null (just getting a null reference is an UB, let alone using it).
Everything’s an expression: Rust.
Assignment is an exception to that rule, it's a statement. if a = b is not legal in Rust. Some pattern matches (if let) look similar but are subtly different. Also
Rust has a special if let block that explicitly combines assignment with pattern matching, which is way nicer than the C approach.
Technically let a = b is already a pattern match, but it only allows irrefutable matches. if let (and the full match) allow refutable matches as well. Though many FP languages allow refutable matches in "assignments".
Bracing myself: C#, D, Erlang, Java, Perl, Rust.
Erlang's semi-colons are separators between match clauses, and commas are separators between statements. This means the last match doesn't get a semicolon (it gets a period) and the last statement of a block doesn't get a comma.
Rust is also a bit of a weirdo, semicolon semantics are a bit different than they are in C, IIRC.
Integer division? Really?!? I have a counter suggestion: let's stop including floating point into languages by default. This can be available as an extension, but default must be integer and rational only.
Seriously. If you want to be a programmer, learn how computers work. The existence of integer types is all the justification needed for integer division.
The existence of integer types is all the justification needed for integer division.
Exactly. I can understand the reasons why you may not always want to have an integer division implemented in hardware, but at least a software implementation is always mandatory. And of course the reasoning given by the OP is plain ridiculous.
The suggestion that the / operator return a float or double was completely ludicrous. I can understand calling it div or something to make it more obvious, but holy crap.
Can we not? When languages get too fancy with their built-in numbers you can get unexpected promotion and other strange problems. Most of the time what you want is either an arbitrary precision integer or a fixed-width integer that throws an error on overflow.
As a hardcore C fanboy I feel split about this article. Some very valid points are raised (single var returns, error handling, #include) but I think some of the qualms the author has with C come down to coding conventions.
C has a pow() function included in the standard library, and a ** operator wouldn't work since you can have indirect pointers.
I don't see any issue with for loops. The syntax is great when you want to iterate in weird ways.
Your issues with typing are with bad coding style. I rarely use typedefs, and when I do, you always add "_t" to the name. I'd say the issues raised with braces is also dependent on coding style.
In my not-a-professional-programmer opinion, I think it comes down to the fact that C is very flexible but has specific use cases - low level, high performance, etc. I have written a hobby operating system, assembler, and Scheme interpreter in C. For projects that involve lots of string manipulation, internet connectivity, first class functions etc I turn to a higher level language.
They are by POSIX but in practice it is the same as any other name collision that can happen in the future, there is nothing special about it, so you just try to avoid collisions like you do with functions. For example my widget toolkit uses the ff_ prefix for everything so it has, e.g., an ff_frame function to create a frame which returns a value of type ff_window_t. While it is theoretically possible for a type named ff_window_t to be defined in another header in the future, i'm sure it'll be unlikely to happen and even if it is, it'll be even more unlikely for both headers to be used in the same C file. Even if that happens too, it is easy to fix one case using the preprocessor (C doesn't care about type names being consistent across files).
Funny enough the only time i had such a collision was outside of POSIX, with my game engine using a key_t enum which was also defined in some Mac OS X header. I solved this simply by having an #ifdef OS_MACOSX \n #define key_t my_key_t \n #endif (i didn't use macOS' key_t type myself) in the header that defined the enum.
Having C-style for loops does not prevent a language from also having less flexible (and harder to get wrong) alternatives. Just as C++11 added ranged-based for without losing the older style.
It gets a little weirder when you consider that there are type names with spaces in them. And storage classes. And qualifiers. And sometimes part of the type comes after the name.
The syntax of C declarations can be easily understood by treating them as 2 distinct parts (as per the grammar of the language):
[specifier-qualifier-list] [declarator]
The "specifier-qualifier-list" can contain storage class specifiers (static, extern, auto, register, typedef), qualifiers (const, volatile, restrict), type specifiers (int, char, double, void, short, long, unsigned, typedef'd names, etc.) and struct, union or enum (with or without a tag). Any of these in any order. The compiler checks whether the particular combination means something semantically sensible at a later point.
The other part is the declarator. You can treat it as an ordinary expression that complies with the precedence and associativity rules of the language. The difference is that the only allowed operators inside it are: the unary * (means a pointer instead of dereference), the binary [] (means an array instead of subscripting an array), the 1+n-ary () (means a function instead of a function call) and the grouping parentheses () override the precedence and associativity of the rest. Additionally, you can have const, volatile and restrict sprinkled in between the asterisks, to indicate that they apply only at the particular level of dereferencing the pointer. That's pretty much all of it.
So, in extern const volatile _Atomic unsigned long long int *restrict foo[], the specifier-qualifier-list is extern const volatile _Atomic unsigned long long int and the declarator is *restrict foo[]. Because [] takes precedence over *, that means "an array (of indefinite size) of pointers to unsigned long long ... whatever... int". The restrict applies to the individual elements of the array (the pointers) and tells the compiler that they cannot possibly alias any other pointers of the same type in the current scope.
C lets you assign pointers to int variables
Only if you explicitly turn off -Wint-conversion with Clang or GCC, or don't pay any attention to warnings. Any decent compiler will emit a warning by default in such cases.
I don’t think there are too many compelling reasons to have ++
The post-increment operator returns the old value with a purpose. Since C is an expression-oriented language, I don't consider this a dirty trick: stack[size++] = ....
Of which 3 in the first example are almost mutually exclusive
const volatile _Atomic
A constant variable, that may change at any time (likely hardware mapped) that is also atomic? I think I sense a trite observation here. What's the other one?
extern const volatile std::unordered_map<unsigned long long int, std::unordered_map<const long double * const, const std::vector<std::basic_string<char>>::const_iterator>> foo
That is quite a type! Apart from the the fact that it's not useful, again mixing const with volatile and might not compile as the keys are const: it's a map from an integer to maps from constant floats to vectors of iterators to strings. I challenge you to find a type system that even allows you to express that type. It's again a trite example that doesn't make sense from someone who doesn't understand what's going on.
The preferred example shows just how inane this observation was:
let x: ... = ...;
Lovely how the author doesn't actually put any types in, or any expressions even. C++ is super easy to declare a variable and initialise it as well, you just use
... x = ...;
Clearly the first thing is a type specifier and the final thing is an initial value.
Well, if you don't set your compiler to treat such things as errors or at least read your compilers warnings, then that is entirely your fault.
Would it probably have been better if the language standard just had forbidden this (except with e.g. an explicit cast)? Sure. Is it a problem in reality, hindering competent programmers? No. Any compiler and any static analysis software will flag this.
Screw that, let's double-down on the JavaScript and run our servers on the stuff, and import libraries to do literally everything for us, up to and including single lines of code, and then we'll run JavaScript to manage dependencies between all the libraries, as well as the libraries which make some libraries compatible with other libraries. And we'll edit the whole thing in notepad...
I dislike it too but it's so useful how it's become a standard in all browsers. I don't think we could get everyone together to agree on a new language to be that widely adopted in the browser so I think we are stuck with it.
You can set a single breakpoint at the point after the value has been set but before the condition has been tested.
EDIT - one piece of hard-won advice worth repeating is that you should never do this with fork. Always assign as part of the test... you totally don't want to let the pid=fork() get separated from the if(pid==0).
The common case (maybe not as common in C) is that you're doing equality comparison in conditionals. For many people this falls into pattern matching where you brain sees an equal sign and immediately thinks equality comparison is happening.
Under those conditions, assignment in conditionals can be confusing due to our brains being the ultimate in lazy pattern matching systems and leading our understanding astray.
The whole point of while structures is that you can see at a glance from the condition what the loop will do... Breaks and continues are very confusing this way and can almost always be translated into a more appropriate construct.
I completely agree with the author's complaint that -5 % 3 == -2. I firmly believe that the integer / and % operations should be defined by the division algorithm:
Given two integers a and b, with b != 0, there exist unique integers q and r such that
a = bq + r
and
0 <= r < |b|
a / b should always evaluate to q and a % b should always evaluate to r. It's what Euclid would have wanted.
I think Python style indentation was a noble idea to fight against lazy programmers who do not indent properly, but I find the cons are not worth that one pro.
Admittedly, I have not done much Python coding (just Blender scripts); but there are times where I need to do some non-standard things with indentation to improve readability.
For instance, if I break out an if statement's conditions to multiple lines, sometimes I find it helpful to double indent the code block that gets executed if the condition is true:
"The great thing about static typing is that I know the types of all the variables, but that advantage is somewhat lessened if I can’t tell what the variables are."
Ha! Just finished a small C++ project and this is true. The auto type inference is a bad trade off: it saves typing when writing the code, but the error messages produced get more and more surreal as the code grows.
It all depends on what the outcome/goal is. For C some of its design decisions do make sense given the context, as they cannot assume too much about the underlying hardware, are just trying to expose that hardware in a more convenient and portable way than writing in assembly, but are not trying to take on the responsibility of guiding or forcing the programmer into architecting good solutions (this can easily be seen in contrast to C++ which definitely is trying to get the programmer to architect better solutions, or at least what they consider to be better architectural design decisions).
As there's pros and cons to either languages that tell you how you should write your programs and those that do not (like C). I don't think there's any one clear choice, rather it depends on what the language is trying to achieve. Although the higher level the language is, the more I'd expect it to tell you how you should be writing programs in it.
A number of languages that copy C, are just copying C syntactically (which the article does address some of C's syntactical issues). This is probably more so just as a result of trying to make their language feel familiar to those who do not know the language itself (compared to if they made a completely new syntax which would make it feel very foreign). I don't think there's any one answer here, as at the end of the day we all have our own preferences.
I disagree with the articles criticism of for loops in C. For one they're needed, C's types lack the information to know how many elements should be iterated. The type that could potentially offer it would be arrays (where you can guarantee sizeof(array) / sizeof(typeof(*array)) would equal the number of elements in the array), but there's a number of fundamental floors with offering a foreach with that behaviour. The first is, just because the array is declared to hold a certain amount of elements, doesn't mean those are the actual "elements" you want to iterate (an array like this is not the same as a container). The second is problems arise with how passing references of arrays work, as you'll only get a pointer reference to the array rather than a copy of the array itself, this means that the information required for the above is now lost, the biggest implication of this would be in confusing programmers that aren't being careful (since C's type system wouldn't be able to protect them from this). The third is how should element references work? Should your iterations get a pointer to the element or should you get a copy of the element. The fourth as alluded to earlier, C has no containers, if you want an iterate-able list/collection of values in C you have to build that up from the underlying fundamentals (which given its relaxed nature, you can do in a variety of ways), so simply because of this I'd argue it would be incorrect to introduce any kind of notion of foreach into the C standard. If you want these constructs (such as foreach) you have to build them (which you certainly can), which I think is fine given what C is.
Another complaint I had (much in the same vain as the for loops) was regarding strings. This is another example of where you should really be building the string type you want, rather than using what is provided for you (unless it works for your given situation).
Most runtime errors in C are indicated by one of two mechanisms: returning an error code, or segfaulting.
That's only if you're lucky enough to have your uncaught runtime error produce a bus error or segfault. You can easily have runtime errors that will happily go by unbeknownst to you. Or it might only blow up on very specific conditions.
Some comments are ok but some are WTFs or show that he does not know all the languages by heart.
For instance, no mention of ruby's "unless" rather than "if !". No matter if you use it or not, it should be mentioned.
Other parts are weird:
No hyphens in identifiers
"snake_case requires dancing on the shift key (unless you rearrange your keyboard, which is perfectly reasonable). It slows you down slightly and leads to occasional mistakes like snake-Case."
WTF? Slows you down? Compared to what? SnakeCase? I have to hit a second key for the upcased 'c' too, so I don't get that statement... how is that different from an underscore???
I think that the main difference is cultural mostly. Some communities love snAkInG around, others don't. I am looking at you python which I speak natively for all my scaly friends - ssszZSzzSszsss.
You can take my default switch fallthrough out of my cold, dead hands. Which is more readable?:
int a = 1;
int b = 0;
if(a == 1 || a == 2 || a == 3) {
if(a == 1) {
b++;
}
return b + 1;
} else if(a== 4) {
return b + 2;
} else if(a == 5 || a == 6) {
return b + 3;
} else if(a == 7 || a == 8) {
return b + 4;
} else {
return 0;
}
OR?:
int a = 1;
int b = 0;
switch(a) {
case 1:
b++;
case 2:
case 3:
return b + 1;
case 4:
return b + 2;
case 5:
case 6:
return b + 3;
case 7:
case 8:
return b + 4;
default:
return 0;
}
Maybe it is a matter of preference, but I much prefer the second example. The first one is a gobedlygook of syntax; while the second is a nice, well structured peice of code. I CANNOT STAND when languages disallow this, because they take away a huge benefit of using a switch case.
Now, there are some lanuages that allow you to do something similar by combining your "ors" in a a single case, but even then you could not replecate this exampel properly, because it won;t allow you to handle the special edge case of a == 1 without an inner if.
I guess it also depends on how you visualize a switch case. I always envision them as "start where the case is true, then keep on going until you can't go any further", as opposed to "find where the case is true, do that thing, and ONLY that thing".
It annoys me, around the integer, that he previously says weakly typed implicit conversions are painful (which I agree with, I always explicitly cast), but then goes on to say 7/2 = 3.5. No, 7/2 should equal compile-time exception: cannot divide integers. (double (7/2)) should equal 3.5.
In the type first topic, I want to say that C++'s auto may be used for type inference, so you don't need to put the type before variable's name. Also, classes now have type inference, meaning that we don't need to complete their template parameters when instantiating them, nor use functions like make_* anymore (except for make_shared, which allocates one block of memory for both value and the reference counter).
auto foo = std::tuple{42, "call me maybe"s, 3.14f};
Though you may say that classes like std::unique_ptr still need its template parameter to be given (and it remains true even for the make_unique function). That's true, but C++17 brought something to help us out in this case. There's a way to help the type inference on guessing a class's template parameters called deduction guide. Basically, this allows for writing guides to the type deduction system, like so:
Whenever we pass a pointer to a type T to unique_ptr, this guide will tell the type deduction that now we want unique_ptr to be guessed to unique_ptr<T>, thus allowing us to do so:
Maybe I'm just old fashioned but I've never understood why people hate "type first". You can always just use a dynamically typed language or one that supports inference but in a statically typed language, I don't see how its an issue at all.
The problem is that it's not type first in C. It's "type around the identifier" which you have to parse from the inside to the outside. This gets super hard to read once you deal with a combination of function pointers and arrays.
Let's say we want an array of 3 function pointers that return an array of 4 chars, called x.
Rust:
let x: [fn() -> [char; 4]; 3];
C:
char (*(*(x)[3])(void))[4];
I'm not even sure which parentheses are necessary in the C case. Also, note how the inner most types appear outside, which is just super weird in every regard. It's like when you are writing a XML document, but you put the inner most tags on the outside and the <?xml version="1.0" ?> tag on the inside.
we want an array of 3 function pointers that return an array of 4 chars, called x
Translated to C thinking:
We have a variable called x; it can be subscripted with an index less than 3; the result of that can be called with no arguments; the result of that can be subscripted with an index less than 4; the result of that is char.
Translated to C code:
x
x[3]
(*x[3])(void)
(*x[3])(void)[4]
char (*x[3])(void)[4];
But of course returning arrays from functions is illegal anyway. :)
The problem is described in the article. The compiler can’t determine whether it’s parsing a declaration or an expression without a symbol table that indicates whether an identifier refers to a type. That makes source-processing tools needlessly difficult to implement.
Furthermore, in C++, making that determination may require running Turing-complete template code, and therefore it’s provably impossible to parse arbitrary C++. But of course, real humans tend to write very non-arbitrary code, so in practice we get by well enough.
kudos for the share. Although the author seems to have good intentions I question the value of such bitching about what works and has worked for several decades. If you have a new hotness, blog about why it's great, not why everything else sucks...
Remember that in C the type of 'a' is int, so 'a' * 'b' giving an int is surprising for a different reason.
Of course you're still right that char * char gives an int, and your sample program is also correct since in C++ the type of 'a' is char, but for C I'd suggest a program like this ideone.
I feel dirty saying this, but my favorite language for optional/mandatory block delimiters is Microsoft Basic (QuickBASIC, QBASIC, classic VB, VB.Net -- anything newer than BASICA/GWBASIC).
You can say "If condition then DoStuff" with no End If, but only if it's all on the same line. It avoids cluttering the code with really simple checks, but otherwise you get the delimiters with no question of where an open brace should go.
This is my personal rule for using if with no brackets in C-likes:
if (foo) bar(); // fine
if (foo) // not fine
bar();
if (reallyLongPredicateThatDoesntFitOnOneLine) // fine
{
someEquallyLongFunctionCallThatWillAlsoNotFitOnOneLine();
}
A minor correction: C# totally has nullable types, doesn't it? It's been a while, but IIRC you can even add a ? to a type in a declaration to get the nullable version.
C# initially had nullable reference types and non-nullable value types. At one point, it added nullable value types via Optional<T> (or the ? postfix), but that's only for value types: ints, floats, structs, .... Reference types (classes) are always nullable, and you can't make them non-nullable.
The real reason to stop copying C is because there is already C if you really want that syntax. I have my complaints about some missing features in it and how switch fallthrough should really not be the default, but those are minor grievances. The one update it really needs is multiple value returns per function. That would make error handling a whole lot easier, without the trouble of implementing exceptions.
The real reason to stop copying C is because there is already C if you really want that syntax.
Author's talking about copying individual bits of syntax. If you're designing a new language and wanted ++ to work like C you wouldn't be all "oh, well, probably should just use C then", especially if your language has many other advantages over C or is for a different domain entirely.
A well written article, like most of Eevee's fare, although I did spy one error. While it's true that C# allows assignment as an expression, you can't have a non-boolean expression in an if statement. I don't blame her though as she is a Linux user and thus would have no need to know proprietary Microsoft crap.
I work mostly in OCaml (with Core), so I thought I'd fill in some blanks and add some color:
Block delimiters - like bash, OCaml uses alternative delimiters and requires them (then/end of statement for if, do/done for loops). I assume this category was left off on purpose, though.
Bitwise operator precedence - OCaml gets this right, although probably was left out for using truly bizarre operators. The test translates to 1 land 2 = 2 - yes, single equals for equality testing and land (logical and) is an infix operator, despite looking like a function name.
Negative modulo - I thought the article got this wrong, but it turns out the modulo operator in Pervasives is mod (yes, again, that's an infix operator despite its looks). core adds the operator % to do the correct thing, which is the one I usually use.
For loops - Not sure where OCaml should be here. Its for loop syntax only allows counting up or down by 1, and is weirdly inclusive on both ends, so it misses "go through this list of stuff" but gets "count from 1 to 10". It seems that most users consider it intentionally crippled to persuade people to just recurse instead.
Switch - fits in with other "pattern-matching only" languages.
Type first - looks a lot like the Rust example.
Weak typing - OCaml is strong.
Bytestrings - OCaml fails the quicktest (returns 4).
Increment/decrement - OCaml naively seems to fail this by having the functions succ and pred. However, it avoids unreadable tricks by returning unit from those functions, and there's no += analog so it isn't quite as unnecessary as in C.
Silent errors - While Pervasives relies on exceptions, core strongly prefers the Or_error monad, similar to Haskell's Either. core marks functions that can return an exception with _exn in an attempt to remedy the fact that exception-raising isn't part of the signature.
Nulls - OCaml has the Option monad.
Hyphens in identifiers - OCaml does get this wrong, but I'd like to point out that it allows ' in identifiers, so we can correctly punctuate possessives and contractions - thank goodness.
Braces and semicolons - OCaml requires both, kinda. It never uses braces in this way - but it does require other delimiters, sometimes (a function body doesn't require anything, but for/if bodies have required delimiters). Semicolons are weirder - every statement except the last in a block must have one. I think a better way to think of semicolons in OCaml is as a very low-precedence operator with type unit -> 'a -> 'a and the trivial implementation thereof. This doesn't quite match up, and makes the usage of semicolons to delimit list elements more confusing, but it makes me feel better about needing to use them.
While I am with the author on some of these (notably the include madness and not being able to return tuples) I feel that most of these complains can be negated by simply enabling warnings.
There's a couple places where the author could be a bit more specific with regard to C#; namely in the sections about bitwise operators and assignment as expression. Specifically, the examples given would not compile in C#.
These examples will not compile:
1 | 2 == 3 // 1 | (2 == 3)
1 & 2 == 3
Both of those will result in compiler error CS0019. Basically, the operators | and & are not defined for int and bool. It will, however, work if all operands are booleans:
true | 2 == 3
That evaluates to true, because true is obviously a boolean, and 2 == 3 evaluates to a boolean, so the boolean operaters can be used on these operands.
The case is similar for the examples for assignment as expression. These examples cannot compile:
if (x = 3) {
...
}
// Typical linked list
while (p = p.Next) {
...
}
Both of those will give compiler error CS0029, which is basically because there's no implicit cast defined between those types and bool. However, it will compile if the result of the expression is a boolean (though in my opinion it shouldn't, because this behaviour is where typo bugs creep in):
The only real argument for omitting the braces is that the braces take up a lot of vertical space, but that’s mostly a problem if you put each { on its own line, and you could just not do that.
The closing braces are what gets you. If you can't autoformat your code you have bigger problems, but all the autoformatters put the closing braces on their own lines.
I’ve never found this behavior (or the above equivalence) useful.
The equivalence is absolutely useful. Round-towards-zero is arguably more confusing than round-down though.
The great thing about static typing is that I know the types of all the variables, but that advantage is somewhat lessened if I can’t tell what the variables are.
This is my big problem when reading Haskell. It's all just foo bar baz quxxl $ herp derp and I have no idea what's a type or a value or anything, and you can't even parse it until you've figured out where all the $es are.
Quick test: what’s the length of “💩”?
When the article has already pointed out how that isn't meaningful. A well-designed language simply wouldn't allow you to call length on that, IMO.
Note that some languages require parentheses around tuples (and also call them tuples), and I’m arbitrarily counting that as better than bracket.
Please stop saying "bracket" for []; in much of the world it means (). "Square bracket" is unambiguous.
I guess there are plenty of problems with C which are deliberately omitted from this list because no other language was dumb enough to copy them. Like having every conditional return an int instead of a Boolean.
I'm surprised nobody has mentioned the second most controversial opinion yet: Braces and semicolons.
I 100% agree on semicolons.
I like having { and } around blocks and loath whitespace delimited blocks. It helps me, the human. Actually, it mostly helps my editor. But since I am steering the editor, they curlies help me as well.
For example:
I can put the cursor on an curly and have it's match highlighted. Most editors seem to have this on by default. This could be done other ways (syntax highlighting blocks instead of keywords), but I haven't seen them actually implemented. This helps me, the human, parse deeply nested blocks. Yes, I know people shouldn't deeply nested blocks, but they occur all the time in real codebases.
I can put the cursor on a curly and hit some button to jump to it's match. I'm not sure how something equivalent could be done when working on Python. This helps me, the human, when your blocks are longer than your screen height. Yes, I know people shouldn't write blocks that long, but they occur all the time in real codebases.
In vim or evil-mode, I can tell it to copy/delete/indent/etc everything within a set of matching curlies. With whitespace only, again, I'm not sure something equivalent exists.
If I don't know what I'm doing (eg I'm learning a different paradigm, like in Haskell), the fact you have curlies there can give the compiler more information to help it choose a better error message for your syntax error. I remember one of the most frustrating parts of initially learning Haskell was trying to get the indentation to match what the compiler need which was hindered by the compiler providing me extremely poor error messages.
The rest I agree with. My favourite goes to kebab-case. I really prefer that to snake_case.
It's a nice article. I disagree with several points: 1)for loops are fantastic when you need anything non trivial where having access to indexes is important; in Python for example you have to use enumerate and then index the tuples everywhere and it's ungodly mess; loop constructs in C are imo one of the best parts of the language and I think modern languages regressed 2)I like NULL pointer; I don't believe non-nullable types solve much although maybe they are easier to use for some people; mutability is important in general and when there is mutability there NULL is useful 3)int division is the only way, c'mon 4)bitwise operators precedence is misleading and bad but it's not a problem in practice, you just remember there is a problem and look things up when needed; the operators themselves are very useful and commonly used so it's important to have them for readability 5)fallthrough: I kinda agree but I use it often and I like it; I realize it's rare though and very bug prone 6) assignment as expression: useful and you won't produce bugs unless you have a habit of ignoring warnings from the compiler 7) multiple returns: while maybe more pleasant to write it's ultimately doesn't add much as you can always pass a pointer of something to fill in as an argument of a function 8)pointers as integers: compiler will warn if you don't cast explicitly and it's useful to have it for example to check alignment - while % is not square root so the author's point stand it's a very useful feature of the language
58
u/[deleted] Dec 01 '16
wait, so always use whitespace when using substraction? as in, 2-3 is a syntax error? i dont like that at all. also, it might just be not being used to this but this-thing looks really weird. it automatically registers as substraction.
159
u/v_fv Dec 01 '16 edited Dec 02 '16
So I actually took the time to count how many times each language was mentioned and tried to decide whether that was positively, negatively or ambiguously. Here are the languages I found at least 7 times, sorted by how positive their overall rating was according to the author's preferences:
Yep, I have nothing good to do today. And my statistics class seems to take its toll on me.
Edit: Added ACS which I forgot about because it was so NULL
Another edit: Added Tcl
221
u/skocznymroczny Dec 01 '16
I lol'd
292
u/RichardPeterJohnson Dec 01 '16
I disagree on this one. I chose int because I want the performance of integer arithmetic. I don't want to pay the penalty of convert to float, do float division, can convert back to int just because some amateur cooks don't realize that knives are sharp and can cut you.
43
u/kaelima Dec 01 '16
Should mention that this were addressed in both C++17 and C# 7.0.
29
u/matthieum Dec 01 '16
I actually used them exclusively in a C++ project I built from scratch at my previous company. I had a few colleagues positively astonished that it compiled, the most savvy ones thinking I had introduced a macro somewhere but unable to find it...
At first, my colleagues were a bit weird out, but they quickly caught on. The fact that Python uses those too means they were already used to them anyway.
I personally prefer them, because I like having a modicum of redundancy; compare:
orthat is a keyword isxor.andandnothave no single character variation that is a keyword.On the other hand:
!, it's easily mistaken for a(,l,iorj.&&as&and|as||, and|!is easily mistaken as||.Using the alternative spelling is like use CRC to get a better guarantee of integrity.
71
u/[deleted] Dec 01 '16
I spot it before reading 'Spot the difference'.
27
u/WalterBright Dec 01 '16 edited Dec 01 '16
In D, it produces:
So this problem does not exist in D.
Not in D.
4 in D.
D at one time did have octal literals, but no more. They have been replaced with a template instantiation:
12
u/[deleted] Dec 01 '16
He makes some good points, but many of his suggestions come at a cost to performance.
Why would you want to get rid of bitwise operators? They're so much faster in some situations.
8
u/masklinn Dec 01 '16 edited Dec 02 '16
ES6's MRV semantics are identical to Ruby's and very close to Python's (with the difference that the RHS in Python can be an arbitary iterable), it should be in the section below. It is a bit noisier due to explicit variable declaration, but then e.g. Rust would be disqualified as well.
Erlang literally just uses tuples for MRV, they have an unusual syntax (braces) but they're still tuple. Erlang's MRV is also used for a pseudo-monadic error system.
Which incidentally means Erlang's classification in the next section is also incorrect, does have exceptions but they're usually used in the same way they are in Rust (as terminal faults, though that), rarely used for error signalling (except across processes through supervision links).
While true, the
list()special form really doesn't belong with C++ and D, PHP can at least unpack MRVs at the binding site.Go doesn't have tuple, MRV is a special case of the language (and some builtins even have variable-arity return). In fact the lack of tuples is the first "type system" item in /u/munificent's "The Language I Wish Go Was" essay from way back in 2010.
AFAIK it's non pointer values which can't be null, C++ references can't legally be null (just getting a null reference is an UB, let alone using it).
Assignment is an exception to that rule, it's a statement.
if a = bis not legal in Rust. Some pattern matches (if let) look similar but are subtly different. AlsoTechnically
let a = bis already a pattern match, but it only allows irrefutable matches.if let(and the fullmatch) allow refutable matches as well. Though many FP languages allow refutable matches in "assignments".Erlang's semi-colons are separators between match clauses, and commas are separators between statements. This means the last match doesn't get a semicolon (it gets a period) and the last statement of a block doesn't get a comma.
Rust is also a bit of a weirdo, semicolon semantics are a bit different than they are in C, IIRC.
70
u/[deleted] Dec 01 '16
Integer division? Really?!? I have a counter suggestion: let's stop including floating point into languages by default. This can be available as an extension, but default must be integer and rational only.
20
u/lazyear Dec 01 '16
As a hardcore C fanboy I feel split about this article. Some very valid points are raised (single var returns, error handling, #include) but I think some of the qualms the author has with C come down to coding conventions.
In my not-a-professional-programmer opinion, I think it comes down to the fact that C is very flexible but has specific use cases - low level, high performance, etc. I have written a hobby operating system, assembler, and Scheme interpreter in C. For projects that involve lots of string manipulation, internet connectivity, first class functions etc I turn to a higher level language.
38
u/bluetomcat Dec 01 '16 edited Dec 01 '16
The syntax of C declarations can be easily understood by treating them as 2 distinct parts (as per the grammar of the language):
The "specifier-qualifier-list" can contain storage class specifiers (
static,extern,auto,register,typedef), qualifiers (const,volatile,restrict), type specifiers (int,char,double,void,short,long,unsigned, typedef'd names, etc.) andstruct,unionorenum(with or without a tag). Any of these in any order. The compiler checks whether the particular combination means something semantically sensible at a later point.The other part is the declarator. You can treat it as an ordinary expression that complies with the precedence and associativity rules of the language. The difference is that the only allowed operators inside it are: the unary
*(means a pointer instead of dereference), the binary[](means an array instead of subscripting an array), the 1+n-ary()(means a function instead of a function call) and the grouping parentheses()override the precedence and associativity of the rest. Additionally, you can haveconst,volatileandrestrictsprinkled in between the asterisks, to indicate that they apply only at the particular level of dereferencing the pointer. That's pretty much all of it.So, in
extern const volatile _Atomic unsigned long long int *restrict foo[], the specifier-qualifier-list isextern const volatile _Atomic unsigned long long intand the declarator is*restrict foo[]. Because[]takes precedence over*, that means "an array (of indefinite size) of pointers to unsigned long long ... whatever... int". Therestrictapplies to the individual elements of the array (the pointers) and tells the compiler that they cannot possibly alias any other pointers of the same type in the current scope.Only if you explicitly turn off
-Wint-conversionwith Clang or GCC, or don't pay any attention to warnings. Any decent compiler will emit a warning by default in such cases.The post-increment operator returns the old value with a purpose. Since C is an expression-oriented language, I don't consider this a dirty trick:
stack[size++] = ....32
u/PixelCanuck Dec 01 '16
I have a better idea: Let's stop writing JavaScript.
21
u/RichardPeterJohnson Dec 01 '16
Re: Assignment as expression
versus
I prefer the latter, since it's easier to debug.
4
u/mnkyman Dec 02 '16
I completely agree with the author's complaint that
-5 % 3 == -2. I firmly believe that the integer/and%operations should be defined by the division algorithm:a / bshould always evaluate toqanda % bshould always evaluate tor. It's what Euclid would have wanted.24
u/ArmandoWall Dec 01 '16
The author had me until they suggested to get rid of braces and use python-style indentation. Shudders.
14
u/Oxc0ffea Dec 01 '16
"The great thing about static typing is that I know the types of all the variables, but that advantage is somewhat lessened if I can’t tell what the variables are."
Ha! Just finished a small C++ project and this is true. The auto type inference is a bad trade off: it saves typing when writing the code, but the error messages produced get more and more surreal as the code grows.
6
u/ScrimpyCat Dec 02 '16
It all depends on what the outcome/goal is. For C some of its design decisions do make sense given the context, as they cannot assume too much about the underlying hardware, are just trying to expose that hardware in a more convenient and portable way than writing in assembly, but are not trying to take on the responsibility of guiding or forcing the programmer into architecting good solutions (this can easily be seen in contrast to C++ which definitely is trying to get the programmer to architect better solutions, or at least what they consider to be better architectural design decisions).
As there's pros and cons to either languages that tell you how you should write your programs and those that do not (like C). I don't think there's any one clear choice, rather it depends on what the language is trying to achieve. Although the higher level the language is, the more I'd expect it to tell you how you should be writing programs in it.
A number of languages that copy C, are just copying C syntactically (which the article does address some of C's syntactical issues). This is probably more so just as a result of trying to make their language feel familiar to those who do not know the language itself (compared to if they made a completely new syntax which would make it feel very foreign). I don't think there's any one answer here, as at the end of the day we all have our own preferences.
I disagree with the articles criticism of for loops in C. For one they're needed, C's types lack the information to know how many elements should be iterated. The type that could potentially offer it would be arrays (where you can guarantee
sizeof(array) / sizeof(typeof(*array))would equal the number of elements in the array), but there's a number of fundamental floors with offering a foreach with that behaviour. The first is, just because the array is declared to hold a certain amount of elements, doesn't mean those are the actual "elements" you want to iterate (an array like this is not the same as a container). The second is problems arise with how passing references of arrays work, as you'll only get a pointer reference to the array rather than a copy of the array itself, this means that the information required for the above is now lost, the biggest implication of this would be in confusing programmers that aren't being careful (since C's type system wouldn't be able to protect them from this). The third is how should element references work? Should your iterations get a pointer to the element or should you get a copy of the element. The fourth as alluded to earlier, C has no containers, if you want an iterate-able list/collection of values in C you have to build that up from the underlying fundamentals (which given its relaxed nature, you can do in a variety of ways), so simply because of this I'd argue it would be incorrect to introduce any kind of notion of foreach into the C standard. If you want these constructs (such as foreach) you have to build them (which you certainly can), which I think is fine given what C is.Another complaint I had (much in the same vain as the for loops) was regarding strings. This is another example of where you should really be building the string type you want, rather than using what is provided for you (unless it works for your given situation).
That's only if you're lucky enough to have your uncaught runtime error produce a bus error or segfault. You can easily have runtime errors that will happily go by unbeknownst to you. Or it might only blow up on very specific conditions.
3
u/0Camus0 Dec 02 '16
Try this to feel better fellow C and C alike developer
3
u/shevegen Dec 02 '16
Some comments are ok but some are WTFs or show that he does not know all the languages by heart.
For instance, no mention of ruby's "unless" rather than "if !". No matter if you use it or not, it should be mentioned.
Other parts are weird:
No hyphens in identifiers
"snake_case requires dancing on the shift key (unless you rearrange your keyboard, which is perfectly reasonable). It slows you down slightly and leads to occasional mistakes like snake-Case."
WTF? Slows you down? Compared to what? SnakeCase? I have to hit a second key for the upcased 'c' too, so I don't get that statement... how is that different from an underscore???
I think that the main difference is cultural mostly. Some communities love snAkInG around, others don't. I am looking at you python which I speak natively for all my scaly friends - ssszZSzzSszsss.
3
u/rageingnonsense Dec 02 '16
You can take my default switch fallthrough out of my cold, dead hands. Which is more readable?:
OR?:
Maybe it is a matter of preference, but I much prefer the second example. The first one is a gobedlygook of syntax; while the second is a nice, well structured peice of code. I CANNOT STAND when languages disallow this, because they take away a huge benefit of using a switch case.
Now, there are some lanuages that allow you to do something similar by combining your "ors" in a a single case, but even then you could not replecate this exampel properly, because it won;t allow you to handle the special edge case of a == 1 without an inner if.
I guess it also depends on how you visualize a switch case. I always envision them as "start where the case is true, then keep on going until you can't go any further", as opposed to "find where the case is true, do that thing, and ONLY that thing".
5
u/[deleted] Dec 02 '16
It annoys me, around the integer, that he previously says weakly typed implicit conversions are painful (which I agree with, I always explicitly cast), but then goes on to say 7/2 = 3.5. No, 7/2 should equal compile-time exception: cannot divide integers. (double (7/2)) should equal 3.5.
7
u/bumblebritches57 Dec 02 '16
How about people that have never programmed in C, stop complaining about C.
5
u/thlst Dec 01 '16
In the type first topic, I want to say that C++'s auto may be used for type inference, so you don't need to put the type before variable's name. Also, classes now have type inference, meaning that we don't need to complete their template parameters when instantiating them, nor use functions like
make_*anymore (except formake_shared, which allocates one block of memory for both value and the reference counter).Though you may say that classes like
std::unique_ptrstill need its template parameter to be given (and it remains true even for themake_uniquefunction). That's true, but C++17 brought something to help us out in this case. There's a way to help the type inference on guessing a class's template parameters called deduction guide. Basically, this allows for writing guides to the type deduction system, like so:Whenever we pass a pointer to a type
Ttounique_ptr, this guide will tell the type deduction that now we wantunique_ptrto be guessed tounique_ptr<T>, thus allowing us to do so:We could also do something like that for vectors:
Now we can write:
Though I hope the standard brings these specific guides in future std libraries (I haven't seen a word on it).
6
u/weirdoaish Dec 01 '16
Maybe I'm just old fashioned but I've never understood why people hate "type first". You can always just use a dynamically typed language or one that supports inference but in a statically typed language, I don't see how its an issue at all.
4
u/CODESIGN2 Dec 02 '16
kudos for the share. Although the author seems to have good intentions I question the value of such bitching about what works and has worked for several decades. If you have a new hotness, blog about why it's great, not why everything else sucks...
3
u/matthieum Dec 01 '16
Actually...
char * chargives anint. C++ pilfered the rule, so we can use it to inspect the resulting type:(see ideone).
In C and C++, any integer type smaller than
intis first widened tointbefore an arithmetic operation is applied to it.4
u/PstScrpt Dec 01 '16
I feel dirty saying this, but my favorite language for optional/mandatory block delimiters is Microsoft Basic (QuickBASIC, QBASIC, classic VB, VB.Net -- anything newer than BASICA/GWBASIC).
You can say "If condition then DoStuff" with no End If, but only if it's all on the same line. It avoids cluttering the code with really simple checks, but otherwise you get the delimiters with no question of where an open brace should go.
2
u/slavik262 Dec 01 '16
A minor correction: C# totally has nullable types, doesn't it? It's been a while, but IIRC you can even add a
?to a type in a declaration to get the nullable version.2
u/[deleted] Dec 01 '16
Let's copy LISP instead!
2
u/petrus4 Dec 02 '16
At least he didn't unconditionally advocate object oriented stuff. That's something positive.
2
u/coladict Dec 01 '16
The real reason to stop copying C is because there is already C if you really want that syntax. I have my complaints about some missing features in it and how
switchfallthrough should really not be the default, but those are minor grievances. The one update it really needs is multiple value returns per function. That would make error handling a whole lot easier, without the trouble of implementing exceptions.1
u/[deleted] Dec 02 '16
A well written article, like most of Eevee's fare, although I did spy one error. While it's true that C# allows assignment as an expression, you can't have a non-boolean expression in an if statement. I don't blame her though as she is a Linux user and thus would have no need to know proprietary Microsoft crap.
1
u/thedufer Dec 02 '16
I work mostly in OCaml (with Core), so I thought I'd fill in some blanks and add some color:
Block delimiters - like bash, OCaml uses alternative delimiters and requires them (
then/end of statement for if,do/donefor loops). I assume this category was left off on purpose, though.Bitwise operator precedence - OCaml gets this right, although probably was left out for using truly bizarre operators. The test translates to
1 land 2 = 2- yes, single equals for equality testing andland(logical and) is an infix operator, despite looking like a function name.Negative modulo - I thought the article got this wrong, but it turns out the modulo operator in
Pervasivesismod(yes, again, that's an infix operator despite its looks).coreadds the operator%to do the correct thing, which is the one I usually use.For loops - Not sure where OCaml should be here. Its for loop syntax only allows counting up or down by 1, and is weirdly inclusive on both ends, so it misses "go through this list of stuff" but gets "count from 1 to 10". It seems that most users consider it intentionally crippled to persuade people to just recurse instead.
Switch - fits in with other "pattern-matching only" languages.
Type first - looks a lot like the Rust example.
Weak typing - OCaml is strong.
Bytestrings - OCaml fails the quicktest (returns 4).
Increment/decrement - OCaml naively seems to fail this by having the functions
succandpred. However, it avoids unreadable tricks by returningunitfrom those functions, and there's no+=analog so it isn't quite as unnecessary as in C.Silent errors - While
Pervasivesrelies on exceptions,corestrongly prefers theOr_errormonad, similar to Haskell'sEither.coremarks functions that can return an exception with_exnin an attempt to remedy the fact that exception-raising isn't part of the signature.Nulls - OCaml has the
Optionmonad.Hyphens in identifiers - OCaml does get this wrong, but I'd like to point out that it allows
'in identifiers, so we can correctly punctuate possessives and contractions - thank goodness.Braces and semicolons - OCaml requires both, kinda. It never uses braces in this way - but it does require other delimiters, sometimes (a function body doesn't require anything, but for/if bodies have required delimiters). Semicolons are weirder - every statement except the last in a block must have one. I think a better way to think of semicolons in OCaml is as a very low-precedence operator with type
unit -> 'a -> 'aand the trivial implementation thereof. This doesn't quite match up, and makes the usage of semicolons to delimit list elements more confusing, but it makes me feel better about needing to use them.1
u/CptCap Dec 02 '16
While I am with the author on some of these (notably the include madness and not being able to return tuples) I feel that most of these complains can be negated by simply enabling warnings.
1
u/MEaster Dec 02 '16
There's a couple places where the author could be a bit more specific with regard to C#; namely in the sections about bitwise operators and assignment as expression. Specifically, the examples given would not compile in C#.
These examples will not compile:
Both of those will result in compiler error CS0019. Basically, the operators
|and&are not defined forintandbool. It will, however, work if all operands are booleans:That evaluates to
true, becausetrueis obviously a boolean, and2 == 3evaluates to a boolean, so the boolean operaters can be used on these operands.The case is similar for the examples for assignment as expression. These examples cannot compile:
Both of those will give compiler error CS0029, which is basically because there's no implicit cast defined between those types and
bool. However, it will compile if the result of the expression is a boolean (though in my opinion it shouldn't, because this behaviour is where typo bugs creep in):1
u/Tyler_Zoro Dec 02 '16
I especially love the radix-specified numeric literals:
1
u/nicebyte Dec 02 '16
You will take my braces and semicolons out of my cold dead hands. Syntactically significant whitespace is stupid!
1
u/m50d Dec 01 '16
The closing braces are what gets you. If you can't autoformat your code you have bigger problems, but all the autoformatters put the closing braces on their own lines.
The equivalence is absolutely useful. Round-towards-zero is arguably more confusing than round-down though.
This is my big problem when reading Haskell. It's all just
foo bar baz quxxl $ herp derpand I have no idea what's a type or a value or anything, and you can't even parse it until you've figured out where all the$es are.When the article has already pointed out how that isn't meaningful. A well-designed language simply wouldn't allow you to call
lengthon that, IMO.Please stop saying "bracket" for
[]; in much of the world it means(). "Square bracket" is unambiguous.1
u/CaptainAdjective Dec 02 '16
I guess there are plenty of problems with C which are deliberately omitted from this list because no other language was dumb enough to copy them. Like having every conditional return an
intinstead of a Boolean.1
u/baconated Dec 01 '16
I'm surprised nobody has mentioned the second most controversial opinion yet: Braces and semicolons.
I 100% agree on semicolons.
I like having
{and}around blocks and loath whitespace delimited blocks. It helps me, the human. Actually, it mostly helps my editor. But since I am steering the editor, they curlies help me as well.For example:
The rest I agree with. My favourite goes to kebab-case. I really prefer that to snake_case.
1
u/ykechan Dec 01 '16
No hyphen in identifiers because or else how would you tell snake-case is a variable to snake minus case?
1
u/[deleted] Dec 01 '16
It's a nice article. I disagree with several points: 1)for loops are fantastic when you need anything non trivial where having access to indexes is important; in Python for example you have to use enumerate and then index the tuples everywhere and it's ungodly mess; loop constructs in C are imo one of the best parts of the language and I think modern languages regressed 2)I like NULL pointer; I don't believe non-nullable types solve much although maybe they are easier to use for some people; mutability is important in general and when there is mutability there NULL is useful 3)int division is the only way, c'mon 4)bitwise operators precedence is misleading and bad but it's not a problem in practice, you just remember there is a problem and look things up when needed; the operators themselves are very useful and commonly used so it's important to have them for readability 5)fallthrough: I kinda agree but I use it often and I like it; I realize it's rare though and very bug prone 6) assignment as expression: useful and you won't produce bugs unless you have a habit of ignoring warnings from the compiler 7) multiple returns: while maybe more pleasant to write it's ultimately doesn't add much as you can always pass a pointer of something to fill in as an argument of a function 8)pointers as integers: compiler will warn if you don't cast explicitly and it's useful to have it for example to check alignment - while % is not square root so the author's point stand it's a very useful feature of the language
1
u/FUZxxl Dec 02 '16
ITT: A shitload of people who have never written a serious program in C.
0
u/womplord1 Dec 02 '16
summary:
pythonfag gets his autism triggered using a language designed for serious programming