115 points · by signa11 · 8y ago · 76 comments
I do think this is even more concise than they would have written in maintained code. In particular, I believe the missing {}'s for the 'while' and 'for' loops whouldn't have been left away, but I might be mistaken. Compare, for example, with this gem:
https://www.cs.princeton.edu/courses/archive/spr09/cos333/be... (submitted as https://news.ycombinator.com/item?id=5672875 some time ago)
There Kernighan talks about a piece of code written by Rob Pike for inclusion in a different book; the code was written to be as small as possible while still including some useful functionality. In particular, Pike made well-considered choices about which functionality to include and which to exclude, but there are also some of those expressions that will not be completely transparent to the beginner C programmer. But the goal was writing short code, and clarity came secondary, but also emerged partly as a result of the first.
Lines like that have far too much information density for my old brain, anymore.
Things that went through my poor brain: "Why pre-inc/decrement? Why the +1 on the for? Did he actually get the precedence of the operators correct? Okay, it looks like argc and argv will be mangled if you actually want to do anything else with them. I see comparing to '\0' with no count limit--is there a buffer overrun lurking here?. Does that error handling actually work--that loop can't exit with that condition unless the second clause does something.
And that was like--30 seconds?
I'd assign argc and argv to something else so if I need them later for something they are in their original state. I'd give myself a variable that points to each individual argv on each iteration, and I'd call it something. I'd make the error handling more explicit so if I had to add another case later I wouldn't have to rack my brain about whether the error gets handled. Etc.
Apparently I've become an inflexible, washed-up, old fart because I just don't enjoy writing C code with that kind of puzzle-like quality anymore.
> Why pre-inc/decrement?
as opposed to what? nothing? clearly, the code needs to advance the iterators before dereferencing.
> Why the +1 on the for?
because it's interested in the option name as opposed to the leading dash: argv[0][0] is '-' (see the while above), the switch is looking at argv[0][1].
> Did he actually get the precedence of the operators correct?
not sure what this is about, the only involved expression has explicit parentheses (out of necessity).
> Okay, it looks like argc and argv will be mangled if you actually want to do anything else with them.
yes... and? mutating a local int and a local pointer is bad? how would you go about this without mutating an iterator?
> I see comparing to '\0' with no count limit--is there a buffer overrun lurking here?
nope, it's an array of null-terminated strings.
> Does that error handling actually work--that loop can't exit with that condition unless the second clause does something.
i do not understand what you're pointing at here.
> I'd assign argc and argv to something else so if I need them later for something they are in their original state.
consider they're already local names, and YAGNI. do alias them if you need them later, not because you might one day.
> I'd give myself a variable that points to each individual argv on each iteration, and I'd call it something.
you would give yourself a possible bug and an obligation to keep the two things in sync.
> I'd make the error handling more explicit so if I had to add another case later I wouldn't have to rack my brain about whether the error gets handled.
what is more explicit than
printf("Illegal option %c\n", *s);
?i'd really love to see your preferred version of the snippet from TFA. i posit it'd be two to three times as long, and its total complexity would be similarly increased.
No, why "pre-" instead of "post-"? Is that a real requirement , or is this an old C++ programmer who knows to write pre-crement in order to avoid creating unnecessary copies?
> Did he actually get the precedence of the operators correct?
It's because I see a "chain" of operators and I have to think about it.
> nope, it's an array of null-terminated strings.
Is it? What happens when I pass 256 '-' characters. Or maybe 32767/32768/65535/65536? Or maybe ...
> Does that error handling actually work--that loop can't exit with that condition unless the second clause does something.
If I need to add a second unflagged argument, that error condition test also needs to be updated. It's an annoyance.
A lot of this is no big deal in this code.
The problem is that code is habit. You will carry the habits from short code over to long code. So, when you are now parsing 45 flags and 8 arguments, you will write code the same way and it WILL have bugs.
Kernighan and Ritchie did not need to bother with less profient programmers maintaining their code. They wrote what they and their friends understood, and apparently that was this.
So in short, the GP (bsder) does have a point.
Well it depends a bit. Plan 9 is written very much in this style, but its easy to maintain because it has rules on when to omit things like braces or parens. You learn the rules pretty quickly (or read rob pike's paper) and after reading and using it a bit will make sense and you won't think about it. I would imagine if you just had someone in the group that wrote like this and the rest of you weren't used to it or the rules were applied inconsistently it would be a huge pain to actually deal with. What matters for all styles is that everyone has rules they agree with and actually follow them.
That's the beauty of C. It can both amaze and terrify you at the same time. It's the programming equivalent of Philippe Petit. It's walking on a tight rope between the twin towers without a parachute or safety net.
If anyone here enjoys awe and terror of C, look through the ioccc submissions.
find - hello
find - - hello
find -xnxn hello
find -x -n -x hello
find -xxx -nnn -xn hello
Yes, the code has an impressive logic density, but there's a reason why modern programmers moved away from such style.They don't necessarily need to be. Repeating the same option can either have no effect (|), invert the option (^), or increase something (as in -vvvvv.) IMHO it's a good thing when there are no error cases --- it basically means the entire input space has a defined effect.
Doing something under-defined, by accident, that you'll at some point break because you weren't thinking of that specific edge case when e.g. refactoring, for someone else who didn't actually intend to exercise that edge case but never realized they were doing so as they never received an error... well, not my cup of tea.
Defensive versus total programming. Either have their place, but ...
Thing is most programmers vastly overestimate the case for defensive programming. In practice, most programs need to run. So for instance, the control loop for a nuclear reactor is not defensively programmed. It never, ever, ever gets to yield an error. Why ? Because the system is not "fail-safe". If the program ever were to say "this doesn't make sense, I'm quitting (or otherwise doing nothing)", there is nothing guaranteeing the system is in a safe state, and so it may melt down. A bug that fails to notice a critical condition, and ignores it, on the other hand leaves the system under the control of the operator, and nothing (should) go wrong (meaning the second level checks should catch the problem)
The general guideline is defensive programming when starting up, with a force switch to override it (so the system can be (re)started if operators decide that's the best outcome). Once the program is running, total programming should be your go-to solution. When in doubt, do the best you can and continue on to the next request.
Since I've been programming million qps+ systems, I've learned that there's even nothing wrong with almost totally ignoring errors. You'd be surprised how well the following works: before handling a request, note down the time (using the cheap instruction), then every time you leave your method, check the time. If it's over a timeout, increase a counter, log if not logged in the past 10s, and send an empty reply. This makes the developer's job harder, but makes everybody else a lot happier.
It doesn't matter anymore if a given curiosity (like "-" options) is categorized as a concession or just as the way it's supposed to be. In any way it's the way that makes more sense from a mathematical standpoint. If there really was some client code depending on a curiosity, it's also easy to spot and change. But usually that's not even needed.
And in any case, there's no justification to change the style and make an incomprehensible thicket of vague "abstractions". There's at most one to write slightly more logic.
case 'x':
if(x_set) {
fprintf(stderr, “can’t set x twice”);
err = 1;
} else {
x_set = true;
}
break;
If your machine has 64kB of memory or thereabouts, you may choose to not bother, though.If you like this sort of source code, I'd also recommend looking at the BSD standard utilities --- they have a similar simple and concise style.
Yet there's still one small simplification that can be made: the condition in the inner loop doesn't need "!= '\0'".
If there are many pure-binary options, then putting them in a bitflag is also an easy extension to the present code:
char binopts[] = "abcdefg";
char *opt;
if(opt = strchr(binopts, *s))
options |= 1 << (optidx - opt);
else
// put the switch(*s) here
Nowadays they just haul in the software weenies with their fancy objects and methods. Lost is the subtle art of manipulating arrays of pointers to strings of characters.Indeed, compare with the "modern" way of doing it:
https://github.com/commandlineparser/commandline/tree/master...
...or something slightly simpler (because it's only one file!):
https://github.com/mono/mono/blob/master/mcs/class/Mono.Opti...
It may seem like an exaggeration, but in my experience working with C# and Java, code like that is the norm --- the core functionality is obscured by being scattered amongst a large amount of "fluff" and it's hard to get the whole picture of how it works because the flow jumps around so much. In contrast, the C code in this article can be understood by just staring at it for a little bit --- the entire functionality is contained within less than a dozen lines.
The examples you’ve linked implement much larger set of functionality.
They de-serialize arguments into strongly typed values (validating arguments), validate against unknown commands/options, print various help messages, support globalization, support arrays in a single argument, and lots more.
Sure it’s overkill for a simple app with just a couple of options, but once you have sufficiently complex command line interface, this modern way becomes much simpler than what’s possible with C.
Compare with “old school” way of doing it: https://github.com/gcc-mirror/gcc/blob/master/gcc/opts.c https://github.com/gcc-mirror/gcc/blob/master/gcc/opts-globa... https://github.com/gcc-mirror/gcc/blob/master/gcc/opts-commo...
BTW that thing isn’t even localized, i.e. everything’s US English-only.
cl_options [next_opt_idx].neg_index == opt_idx
old_decoded_options[i].errors & ~CL_ERR_WRONG_LANG
and the parentheses too... why in the world do they do this? set_option (opts, (generated_p ? NULL : opts_set),
opt_index, value, arg, kind, loc, dc);Personally, I don’t write code like this, because I spam “autoformat” hotkey in the IDE :-)
Often, a program's layout reflected the programmer's inner thoughts as he or she worked through the creation of the code. Expressions were written like a mathematician might write, with spacing and bracketing reflecting some way of thinking about the grouping of the abstractions at hand.
This is just a random routine, written around 1975, from Niklaus Wirth's PL/0 compiler for Pascal, the programming language that he created. The indenting is wild by contemporary standards:
procedure getch;
begin if cc = ll then
begin if eof(input) then
begin write(' program incomplete'); goto 99
end;
ll := 0; cc := 0; write(cx: 5,' ');
while not eoln(input) do
begin ll := ll+1; read(ch); write(ch); line[ll]:=ch
end;
writeln; readln; ll := ll + 1; line[ll] := ' ';
end;
cc := cc+1; ch := line[cc]
end {getch};
Early C code too, even in the Unix kernel, was often dense and hard to understand (the kernel was under 10,000 lines back then). See Lions' Commentary [2]. Here's a small function, setfs(), line 7167 of the system 6 Unix kernel in Lion's book. In particular note the lack of indention under the for loop: setfs(dev)
{
register struct mount *p;
register char *n1, *n2;
for(p = &mount[0]; p < &mount[NMOUNT]; p++)
if(p->m_bufp != NULL && p->m_dev == dev) {
p = p->m_bufp->b_addr;
n1 = p->s_nfree;
n2 = p->s_ninode;
if(n1 > 100 || n2 > 100) {
prdev("bad count, dev);
p->s_nfree = 0;
p->s_ninode = 0;
}
return(p);
}
panic("no fs");
}
It seems obvious now that standard and consistent formatting make programs easier to understand. Why did we old timers do that to ourselves? First, short programs were easier to keypunch or enter via a teletype machine. Second, we had a plenty of time to study our code. Turn around time for a compilation, from submission to printed listing, could take 30 minutes to 12 hours.[1] http://pascal.hansotten.com/niklaus-wirth/pl0/
[2] John Lions, Lion's Commentary on Unix 6th Edition with Source Code. https://www.amazon.com/Lions-Commentary-Unix-John/dp/1573980...
I believe this would cause the newline not to be printed in the unknown command error, so it is necessary.
This is true in C++ but not in C.
That means that (*argv)[0] is the first character of the program name and (*argv)[1] is the first character of the first argument.
(*argv)[1] is the second character of the program name (in this case), not first character of first argument. D)
Debug=true
;;
d)
Destination="$OPTARG"
;;
esac
done
shift `expr $OPTIND - 1` # I did not use $((OPTIND - 1)) for a reason!
Bam! Your program will now behave exactly as every other UNIX executable, especially if you do not name it with .sh postfix and make it executable, the user won't be able to tell the difference between it or say, ls(1)!
Having said that, the example in the article cements what I've been saying all along: C is more than fine in the programming hands of a thoughtful mind. int i=0;
while(i < args.Length-1 && args[i][0] == `-`) {
for (var j=1; j<args[i].Length; j++) {
switch(args[i][j]) { case `x`: ...ARGBEGIN{ default: usage(); case 'm': m = ARGF(); break; case 'p': pflag = 1; break; }ARGEND
https://github.com/9fans/plan9port/blob/master/include/libc.... https://github.com/9fans/plan9port/blob/master/src/cmd/mkdir...
btw, many of the plan 9 commands use slightly different/custom option parsing. probably for historic reasons.
This is something I have never understood.
I am a connoisseur of command line progams. I have used hundreds of them over decades. I write command line programs and scripts every week. It is an obsession. Yet I am embarassed to admit that honestly I have never understood the benefits of flexibility with passing arguments. I never understood the "getopt" movement. I do not use it. All my programs are very simple and straightforward without heaps fo options.
I apologise for being obtuse, but what am I missing?
To anyone who might be offended: I am not criticising flexibility of commandline arguments or its coolness. I just want to understand what are the practical advantages over something more simple and less flexible, like what I prefer. Only if I understand the advantages can I be an advocate for using numerous commandline options and flexibile parsing.
(Theres another post about setenv et al. on the front page right now. For programs that read from environ variables -- which can be a better alternative to using heaps of commandline options IMO -- I just use envdir from daemontools.)
It's about not having to remember what goes before what, if you can put them like this or that, etc ON TOP of remembering the arguments themselves.
>All my programs are very simple and straightforward without heaps fo options.
If your programs are basically ./a.out then perhaps you're not the target audience for getopts?
$ FOO=BAR THIS=THAT ./myprog
I think the hyphen syntax for arguments once was primarly useful for interactive use; it still is, but GNU-style long arguments and hundreds of options seem increasingly absurd. for (String next = in.readLine();
next != null && dictionary.add(next);
next = in.readLine());
...you can sense my contempt for this assignment. I would of course never do this in a real program.I wouldn't be surprised if it let a bunch of unexpected inputs through as another commentor pointed out.
That may have been okay back then but in today's hostile environment and with so many people around that aren't natural programmers who dream of pointers you probably want something a bit more verbose.
I've been programming C since the late 80s so I'm not a new-comer. But I'm not a fan of that code even though I can understand it okay.
The more experience I get and the more people I work with, the simpler I like my code to be. I'll always take simplicity over speed and concision if I can.
while (--argc > 0 && (*++argv)[0] == '-')
...
Notice that the decrement always occurs before the ‘>’ is
evaluated. This would be true even if it were postfix (i.e., argc-- > 0).
but isn't the last statement ("This would be true even if...") in error?
IIRC a post-decrement would occur after the ‘>’ is evaluated.edit: clarity
Granted pointers, just like objects in more "modern" languages, take some while for new programmers a while to get their heads around.
Interesting point, and I agree. I read that code a little earlier today, and (was a bit surprised to see that) I could understand it pretty much right away, even though I have not used C a lot for a while. I did use it a lot earlier though, on both Unix and DOS/Windows, and I do remember poring over that K&R book early in my C career, and working out the meaning of each line of code in almost the whole book. That may be why I could figure out quickly what it meant, now. More cryptic stuff might take a while to figure out, though, but the point I want to make is that the general principle remains the same: you have to understand what each line and even what each token (of the code) in each line is doing, how it works, etc., by reading the books and docs, by trial and error, modifying the code and seeing the modified output, using debugging print statements, isolating smaller chunks of code and running them to see how they work and if your mental model of what is happening matches reality, etc.
Even BASIC had them via peek and poke.
Don't people learn to draw boxes and arrows anymore?
When you sit down and just design a piece of code for hours as to not waste your compilation cycle, I would guess that you naturally end up being fairly crafty after some time.
When I learned C it was a given to code efficiently. Pointer manipulation and efficient structure packing was expected, and therefore taught. You'd rule out of an interview anyone who didn't easily grok it.
It's probably no surprise that the fastest GUI editor I've used to date ran on a 7.1MHz machine. Such is "progress"!
Many of the modern conveniences might be expressive in the small (function level). But it quickly gets highly unexpressive as you move to a more global level. That is because this "expressiveness" is often achieved by arbitrary and non-orthogonal approaches, which increases dependencies and hinders modularity. In the end, it's only more convenient to paint yourself into a corner. Seen that in many codebases.