8 ms·
How Old School C Programmers Process Arguments
- QShift 9y agoSkimmed through the article and found a small mistake. 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.
- ateesdalejr 9y agoWow, the amount of compactness and craftsmanship in these lines of code is amazing.
- jstimpfle 9y agoI think there's nothing magical about it at all. It's rather that "modern software architecture" (examples for what I mean linked in another comment here about C# and Java) is a disaster.
- beefhash 9y agoIt might not even be that. I presume that kind of code used to be written with pen and paper, a compilation cycle almost prohibitively expensive. 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.
- oldcynic 9y agoNope, you just end up thinking that compactly as you type. 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"!
- tech2 9y agoJust because I'm curious, CygnusEd?
- oldcynic 9y agoYes indeed. :) Most impressive, I think, is that it managed to be so fast and include smooth scrolling.
- vram22 9y agoBrief was pretty fast too. I only used it briefly (heh), but read in some computer magazines at the time, that it used a lot of code optimizations, one of which was that it used assembly language code, and another being (IIRC) that it used BIOS calls to dynamically change the speed of movement of the cursor when it detected that you pressed an arrow key for a longer time (probably by changing the key repeat rate or reducing the repeat time), so that when you did that, movement through the file would be faster. The idea being that a user pressing the arrow key for a longer time probably meant to move through a longer section of the file (than usual) to reach some other distant place in it, so Brief figures this out and assists them with that, by scrolling faster with that BIOS technique. Anecdote: On a trip to the US (Boston), I once met Norm Miles, who, my US colleague said, was the creator of Brief. The Brief editor is actually still available, here, and for free now: http://www.briefeditor.com/ http://www.briefeditor.com/ https://en.wikipedia.org/wiki/Brief_(text_editor) https://en.wikipedia.org/wiki/Brief_(text_editor)
- lazyjones 9y agoAmazing from today's perspective, but not surprising. With just a few KB of memory, minimalistic rather than modern expressive style was just natural.
- jstimpfle 9y agoI get cynic when "modern style" approaches with their megabytes and gigabytes of junk code that does nothing (or nothing anyone could clearly define) is called "expressive". 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.
- yongjik 9y agoSo it will admit any combination of -n and -x. In particular, these things won't raise an error: 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.
- setr 9y agoWouldn't an empty flag be caught by the default handler? And duplicate flag usage isn't inherently incorrect (-vvv); handling that would be in the switch statement, and if its actually a boolean switch, then duplicates would just be ignored anyways, so harmless.
- kstenerud 9y agoThe empty flag(s) would be processed by *s != '\0' and result in noops. The point in the early days wasn't to handle corner cases like these gracefully. That only came later as the audience for shell commands widened.
- userbinator 9y agoIn particular, these things won't raise an error 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.
- MaulingMonkey 9y agoRaising an error is an intentionally 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.
- 9y ago
- userbinator 9y agoExtract this into its own function and you basically have getopt() --- the POSIX version, not the rather more bloaty GNU version that has sometimes-unexpected behaviour (like reordering arguments). 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/src 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.Options/Mono.Options/Options.cs 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.
- vole 9y ago>Yet there's still one small simplification that can be made: the condition in the inner loop doesn't need "!= '\0'". I believe this would cause the newline not to be printed in the unknown command error, so it is necessary.
- userbinator 9y agoHow? '\0' is the same value as 0 (only with a different type, which doesn't matter in this case), and if(x != 0) is the same as if(x).
- ggm 9y agoThe getopt() arguments we used to have on USENET before gnu swept the board..
- blikdak 9y agoOne thing an old school C programmer would not do is neglect to put parens around their blocks.
- enriquto 9y agoOn the contrary! We force all our blocks to consist of a single statement so that we can always omit the damn parens.
- kqr 9y agoAre you saying you need statements in your loop blocks!? I just added this to a school assignment: 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.
- kbob 9y agoRitchie is the person who made the decision to make curlies optional in C. That's strong evidence he wouldn't add extraneous curlies to his code.
- d--b 9y agoMmh, what's so special about this? A C# version is pretty close... 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`: ...
- pjmlp 9y agoThe pointer tricks on argv.
- zoul 9y agoIt’s nice and smart, but also notice how it needs a whole web page to explain and would happily compile after a lot of invisible single-letter changes that would introduce horrible bugs. There is value in the old ways of writing software, I just wouldn’t throw out modern software engineering just yet.
- oldcynic 9y agoAny competent C programmer shouldn't need any explanation of that simple example. Granted pointers, just like objects in more "modern" languages, take some while for new programmers a while to get their heads around.
- pjmlp 9y agoHaving learned pointers in other languages before learning C, I never understood what is so hard about them. Even BASIC had them via peek and poke. Don't people learn to draw boxes and arrows anymore?
- vram22 9y ago>Any competent C programmer shouldn't need any explanation of that simple example. 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.
- deleted 9y ago[deleted]
- Chiba-City 9y agoThe original getopt was a really tight library.
- mjl- 9y agothis is how they did it somewhat later in plan 9, with macro's: ARGBEGIN{ default: usage(); case 'm': m = ARGF(); break; case 'p': pflag = 1; break; }ARGEND https://github.com/9fans/plan9port/blob/master/include/libc.h#L919-L940 https://github.com/9fans/plan9port/blob/master/include/libc.... https://github.com/9fans/plan9port/blob/master/src/cmd/mkdir.c#L57-L71 https://github.com/9fans/plan9port/blob/master/src/cmd/mkdir...
- henesy 9y agoThe Plan 9 solution always felt really logical imo.
- mjl- 9y agoi agree. too "clever", feels like a needless optimization. (optimizing for fewer keystrokes to type? or obscurity?) btw, many of the plan 9 commands use slightly different/custom option parsing. probably for historic reasons.
- mveety 9y agoNo, this isn't clever at all. Its an optimization for when you need to write a lot of little utilities that need to parse arguments. It probably came out of a day of writing tools, and after the fifth time of rewriting that while/for loop someone got pissed and made that macro. I use this macro all the time on both 9front and unix because it makes parsing arguments trivial (and I don't use long options, but that's more because I'm a plan 9/unix extremist than for any technical reasons).
- Annatar 9y ago"That’s how Kernigham and Ritchie did it in 1978. Nowadays they just haul in the software weenies with their fancy objects and methods." No, we use getopts(3C). For decades now. I even use getopts in my shell programs. For old UNIX hands, using getopts in C or in shell programming is certainly nothing new. How, you ask? Simple! Watch this: while getopts hDd: Option do case "$Option" in h) Usage ;; 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.
- cperciva 9y agoOn the topic of processing command-line arguments and the recent post on obscure things you can do with C: My "magic getopt" (http://www.daemonology.net/blog/2015-12-06-magic-getopt.html http://www.daemonology.net/blog/2015-12-06-magic-getopt.html) does some very evil things to make it possible to write a "normal-looking" C getopt look which accepts both short and long options.
- tomsmeding 9y agoI have to say, to reasonably experienced C programmers, this code should be pretty clear. If you need that whole paragraph to understand (* ++argv)[0], you might be an awesome programmer, but you're not yet a reasonably experienced C programmer. ;) 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/beautiful.html https://www.cs.princeton.edu/courses/archive/spr09/cos333/be... (submitted as https://news.ycombinator.com/item?id=5672875 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.
- vultour 9y agoI am not a C programmer, nor a veteran in any other language and this code was pretty clear.
- bsder 9y ago> If you need that whole paragraph to understand (* ++argv)[0], you might be an awesome programmer, but you're not yet a reasonably experienced C programmer. ;) 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.
- aplorbust 9y ago"What's so cool about this is its flexibility." 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.)
- tannhaeuser 9y agoTo add to your point, it's really simple, clear, and flexible to just use environment variables as program arguments, as in $ 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.
- coldtea 9y ago>Yet I am embarassed to admit that honestly I have never understood the benefits of flexibility with passing arguments. 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?
- pjmlp 9y agoEasy to sort out with an help flag.
- cagey 9y agoMaybe I've forgotten more C than I'd like to admit, 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
- kbsletten 9y agoThe decrement is the same either way, the value yielded by the decrement expression would however be different. I don't like the wording either.
- scarface74 9y agoWhat's clever about this? It's a little obtuse and overly permissive. How do most developers parse arguments? I suspect it would be a for loop with nested if statements - since you can't switch on strings. If you expect a value to follow the flag you increment the counter in your if block and 'continue'.
- dajt 9y agoI wasn't all that impressed with the code - too 'clever' and concise for me. 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.