9 ms·
I wrote the least-C C program I could
- edrxty 5y agoYet another pre-processor-to-victory post. Check the header in the source. If we're going to use crazy header files, I want to see someone get the linux kernel to build and boot while including this: https://gist.github.com/aras-p/6224951 https://gist.github.com/aras-p/6224951
- avian 5y ago> #define M_PI 3.2f A long time ago, a friend who was studying mathematics at the time, approached me laughing hysterically and showed me a page in an "intro to C"-style book. It showed an example of how one would write a "get circumference of a circle" function. At the top of the code, there was a #define for the value of pi. The text describing the code said something like this about why pi is #defined and not included directly in the expression: "We define pi as a constant for two reasons: 1) it makes the expressions using it more readable 2) should the value of pi ever change, we will only have to change it in one place in the code"
- abdusco 5y agoThis is just too good. It must be a joke on the author's part :D
- izietto 5y agoActually I find it pretty clever because pi value may change in a programming context, as can change its precision
- jazzyjackson 5y agoWe’ve been wrong before :)
- Hamuko 5y agoWhat, you need more than 3.2f?
- _0w8t 5y agoOn more serious note 22.0/7 or 3.1 in base 7 is a rather good approximation sufficient to quite a few problems and good to calculate things in one’s head.
- crdrost 5y agoFun fact, 22/7 is only accurate to one part in 2,500, or 0.04%, netting you one extra digit (i.e 3.14 is less accurate with 3 digits but 3.142 is more). Most remember 3.14159 which is way better than 22/7, but pi has an even better unusual rational approximation, 355/113 gets you two extra digits, it is accurate to one part in 12 million, or 0.000008% . So you have to go to 3.1415927 to beat it.
- cpeterso 5y agoJPL answers the question: How Many Decimals of Pi Do We Really Need? > For JPL's highest accuracy calculations, which are for interplanetary navigation, we use 3.141592653589793. https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/ https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimal...
- crdrost 5y agoThat's not saying much as it appears to just be double precision, but yeah, rational approximations only save you one or two digits and after a certain point it’s more nerdy to just memorize pi.
- spockz 5y agoBut why is it then 3.2f instead of 3.1? Seeing as 3.14 gets rounded to 3.1. Or is that part of the joke and the reason for why the value nee changing?
- avian 5y agoSorry, I should be more clear. This is a line from the header linked by the parent comment that reminded me of this story.
- masklinn 5y agoRegardless of the actual answer, it can make sense to round it up depending on the use case e.g. if you’re calculating the tolerances for a shaft onto which you place a disk, computing the disk diameter (and thus volume, and weight) to be larger than actual provides a safety margin which rounding down would not. Any additional safety margin added afterwards might not be sufficient in all round-down cases.
- susam 5y agoThere is a similar joke in the book Learning Perl, 3rd Edition by Randal L. Schwartz and Tom Phoenix. I wrote a post about it here fourteen years ago: https://susam.net/blog/from-perl-to-pi.html https://susam.net/blog/from-perl-to-pi.html . Quoting from the book: "It's easier to type $pi than 𝜋, especially if you don't have Unicode. And it will be easy to maintain the program in case the value of ever changes." There is also a comment by Randal Schwartz in the comments section where he credits Tom Phoenix with that particular bit of humour.
- avian 5y agoGood catch! I might be misremembering this event and it was actually Perl, not C. I see Learning Perl, 3rd Edition was published in 2001, which does put its publication at about the right time in early 00s.
- TonyTrapp 5y agoAs funny as it sounds, there is still a bit of truth in there, though: code might change from using floats to double for example, so you might want to replace single-precision constants by double-precision constants. Only need to replace a single pi constant in that case. :)
- lqet 5y agoThis #define would have almost been required by law in Indiana: https://en.wikipedia.org/wiki/Indiana_Pi_Bill https://en.wikipedia.org/wiki/Indiana_Pi_Bill
- jonasenordin 5y agoAdd Pi to locale?
- ChrisRR 5y agoDepends if you're using biblical pi
- deleted 5y ago[deleted]
- spullara 5y agoThat #define is making fun of this: https://www.forbes.com/sites/kionasmith/2018/02/05/indianas-state-legislature-once-tried-to-legislate-the-value-of-pi/?sh=504e95c6260a https://www.forbes.com/sites/kionasmith/2018/02/05/indianas-...
- brian_herman 5y agoCan I do it with an #ifndef?
- ARandomerDude 5y agoI don't quite understand these lines: #define ; #define do I was under the impression it was "#define CNAME value" – what does it mean when there is no value? A trip to Google didn't turn up anything for me, so I'm wondering if a C master can weigh in. Thanks!
- cperciva 5y agoIt defines those to a value of "", effectively stripping them from the source code. The most common place where this sort of thing occurs is the common idiom #ifdef DEBUG #define debug(...) realdebug(__VA_ARGS__) #else #define debug(...) #endif which allows you to sprinkle debug() calls through your code and have them disappear if you compile without defining the macro DEBUG.
- asveikau 5y agoOf course for your quoted use it's more common to see: #define debug(...) ((void)0) This forces you to use debug() as a statement. If no value is defined you could omit the semicolon on a debug() statement and it still compiles.
- AtlasBarfed 5y agoOh my the defines. What is language and semantics? "When I use a word," Humpty Dumpty said, in a rather scornful tone, "it means just what I choose it to mean - neither more nor less." Very ugly, ill-defined, uncodified democracy. No one tells you when you vote, no one counts up the votes, there are no official results. When you speak or communicate with someone else, you are voting with them. "I vote this word means X, for a poor/crude/coarse agreement of what X is the first place." And this is propaganda at its finest. Evil doublespeak: say one thing, and it actually is another. Snuck in. Fantastic. Related: https://github.com/Droogans/unmaintainable-code https://github.com/Droogans/unmaintainable-code
- deleted 5y ago[deleted]
- raverbashing 5y ago> would use the C preprocessor to create his own language and then write the implementation of his language in that self-defined language Yeah that sounds like the easiest way to make your colleagues hate you I "love" how we had more languages in the 70s (usually created as a one-off project for people with not so much user friendliness in mind) think m4, awk, tcl, etc
- na85 5y agoAwk is actually great. M4 not so much. Some absolute lunatic solved this year's Advent of Code in m4; it was impressive.
- erik_seaberg 5y agoTerraform module args used to be very limited, and I didn’t know how to generate JSON it would take instead of HCL, so I actually used m4 to avoid repeating every template n times. And now we are sad because of course Terraform has improved quite a bit.
- na85 5y agoI used to contribute to an ultima online emulator and I definitely used awk to generate C# classes from a CSV file.
- ThinBold 5y agoI mean we do have a lot of (perhaps too many) markdown dialects today. Wikipedia, wordpress, github, stackexchange, you name it. Last time I was using a Q&A forum for calculus course, it uses $$ to start and close a MathJax div.
- can16358p 5y agoIn header file's line 12, is there two different semicolons? Is one of them actually semicolon-looking another Unicode character? (https://github.com/ibara/cpaint/blob/21c70acba373df932920d5f9029187d1680a29ad/cpaint.h#L12 https://github.com/ibara/cpaint/blob/21c70acba373df932920d5f...)
- ThinBold 5y agoU+FF1B Fullwidth semicolon. The semicolon in CJKV ideographs.
- johndoe0815 5y agoSteve Bourne used a set of macros to enable ALGOL-like programming in C and used it to implement his Unix shell - https://research.swtch.com/shmacro https://research.swtch.com/shmacro
- agumonkey 5y agoha, I was googling FORTRAN C macros and went nowhere, that was the page I was looking for :)
- OskarS 5y agoThis is obviously terrible, but my favorite part of this whole thing is the fact that he included the parentheses in the IF/THEN macros, so you didn't have to do it for the condition in the if statement. So, like, this line doesn't need parentheses around the condition: IF (n=to-from)<=1 THEN return FI All modern languages that try and do a refresh on the C style (Rust and Swift notably) do this, it's clearly the right idea. They should just update the C and C++ syntax to make those parentheses optional at this point. (PS. some people would also recoil at the assignment-as-expression used in that line, but that's just good clean fun!)
- josefx 5y agoThey already make them optional for single nested statements, which causes a gigantic mess when you extend code and forget to add them. if (a) doThis(); andThat(); is interpreted as if(a){ doThis(); } andThat(); Some compilers are nice enough to throw around misleading indentation warnings, but without an explicit block termination like FI this just causes issues all over the place.
- skocznymroczny 5y agohe meant making the (a) part optional to make "if a" instead. parenthesis are (), {} are braces :)
- 5y ago
- DougBTX 5y agoA “least-C” needs lazy evaluation at a minimum :-)
- ivxvm 5y agoMy thoughts exactly. It's just C with a slightly different syntax. Would be way more interesting if it was using lazy evaluation, or maybe some other kind of term rewriting, possibly with garbage collection or some smart miniature region based memory management.
- fhars 5y agoI do like the style of kona if I need an example to confuse people about how C looks like, https://github.com/kevinlawler/kona/tree/master/src https://github.com/kevinlawler/kona/tree/master/src
- BruceEel 5y agoThere was the "Val Linker"[1] (also for the Amiga, though I can't seem to find that version), written in a kind of Pascal-ish C, powered by macros.. Snippet: void get_order_token() BeginDeclarations EndDeclarations BeginCode While token_break_char Is ' ' BeginWhile order_token_get_char(); EndWhile; copy_string(token, null_string); If IsIdentifier(token_break_char) Then While IsIdentifier(token_break_char) BeginWhile concat_char_to_string(token, token_break_char); order_token_get_char(); EndWhile; lowercase_string(token); Else If token_break_char Is '[' Then While token_break_char IsNot ']' BeginWhile concat_char_to_string(token, token_break_char); order_token_get_char(); EndWhile; order_token_get_char(); If case_ignore.val Then lowercase_string(token); EndIf; Else concat_char_to_string(token, token_break_char); order_token_get_char(); EndIf; EndIf; return; EndCode *1 https://ftp.sunet.se/mirror/archive/ftp.sunet.se/pub/simtelnet/msdos/pgmutl/val_link.zip https://ftp.sunet.se/mirror/archive/ftp.sunet.se/pub/simteln...
- auvi 5y agoIf I remember correctly, the first Bourne Shell was written in a Pascal-ish C.
- agumonkey 5y agoIt's interesting, first time I wrote C was after learning programming through Java. My "C" code was all new_<type>(..) .. I couldn't not think in Java syntax.
- WalterBright 5y ago> I use lots of characters that look like ASCII but are in fact not ASCII but nonetheless accepted as valid identifier characters. Clever, I was wondering how the : was done, but it's an abomination :-/ With some simple improvements to the language, about 99% of the C preprocessor use can be abandoned and deprecated.
- BruceEel 5y agoWalter, D has conditional compilation, versioning and CTFE without preprocessor so I guess that covers the 99% "sane" functionality. Where do you draw the line between that and the 1% abomination part, i.e. your thoughts on, say, compile time type introspection and things like generating ('printing') types/declarations?
- WalterBright 5y agoThe abomination is using the preprocessor to redefine the syntax and/or invent new syntax. Supporting identifier characters that look like `:` is just madness. Of course, I've also opined that Unicode supporting multiple encodings for the same glyph is also madness. The Unicode people veered off the tracks and sank into a swamp when they decided that semantic information should be encoded into Unicode characters.
- foxfluff 5y ago> The Unicode people veered off the tracks and sank into a swamp when they decided that semantic information should be encoded into Unicode characters. As if that weren't enough, they also decided to cram half-assed formatting into it. You got bold letters, italics, various fancy-style letters, superscripts and subscripts for this and that.. all for the sake of leagacy compatibility. Unicode was legacy right from the beginning.
- WalterBright 5y agoYeah, where do you stop when you start adding fonts to Unicode?
- oefrha 5y agoWell, pasting the code into VS Code ruined some of the fun, since the non-ASCII homoglyphs are now highlighted by default.
- tromp 5y agoLennart Augustsson once wrote the least-Haskell Haskell program, amazingly without the help of a preprocessor: https://augustss.blogspot.com/2009/02/regression-they-say-that-as-you-get.html https://augustss.blogspot.com/2009/02/regression-they-say-th... And to answer the question in the top comment: https://hackage.haskell.org/package/BASIC-0.1.5.0/docs/Language-BASIC.html https://hackage.haskell.org/package/BASIC-0.1.5.0/docs/Langu...
- CapsAdmin 5y agoThere's also https://libcello.org/ https://libcello.org/ a popular (?) macro-heavy library which makes C feel modern.
- lionkor 5y ago"modern" meaning less explicit?
- retrac 5y agoMeaning classes, algebraic data types, pattern matching, boxed objects, iterators and garbage collection. All they need is smart pointers or a borrow checker and it'd practically be C++ or Rust, except it's rather brittle because it's just a bunch of macros.
- foxfluff 5y agoHave you ever seen it used in the wild?
- favorited 5y agoTheir FAQs say that's unlikely: > Is anyone using Cello? > People have experimented with it, but there is no high profile project I know of that uses it. Cello is too big and scary a dependency for new C projects if they want to be portable and easy to maintain.
- omgmajk 5y agoHasn't everyone done at least something similar to this? I'm surprised, I re-define C quite often when I'm bored.
- marcodiego 5y agoI once saw a C header that defined "BEGIN" as {, "END" as } and other pascalisms. I find it difficult to understand how some people are so stubborn to change their model of thinking.
- bombcar 5y agoI believe I’ve seen stuff like this used as partial help when transcribing a program from pascal or Fortran to C, from before the era of automatic tooling to help. Whether they’d ever go back and finish the migration is not known.
- pickledcods 5y agoThe biggest pitfall with manual bulk transcribing Pascal to C back in day, was that operator precedence between both languages are really different. Not only is their model of thinking different, it is also wrong.
- snarfy 5y agocpaint.h #include<curses.h> #include<stdio.h> #define ; #define do #define ʌ * #define N -1 #define call #define main. #define , ]; #define ꞉= = #define = == #define ; ]; #define not ! #define I int #define M 256 #define or || #define end ;} #define CALL } #define S case #define X x<<8 #define size [ #define <> != #define var int #define Y y<<16 #define begin { #define F FILE*f #define ꞉integer #define POOL ;}} #define W p[y*q+x] #define Z (W&(M N)) #define packed char #define OK break;case #define procedure int #define fill꞉= return #define close fclose(f) #define readln(a) c=fgetc(f) #define H(a,b) mvaddch(a,b,' ') #define writeChar(a) fputc((a),f) #define open(a,b) F=fopen((a),(b)) #define A(a) attron(COLOR_PAIR(a)) #define B(a) attroff(COLOR_PAIR(a)) #define read(a) switch(getch()){case #define draw(a) {W=Y;W|=X;W|=((a)&0xff);} #define LOOP for(y=0;y<w;y++){for(x=0;x<q;x++){ #define check if(fgetc(f)!=83){fclose(f);return N;};w=fgetc(f);q=fgetc(f) #define start initscr();clear();keypad(stdscr,TRUE);cbreak();noecho();curs_set(0)
- Koshkin 5y agoI once wrote a set of macros to emulate the syntax of Oberon, and then used that to write some code that could later be easily converted to real Oberon. It was a fun exercise - highly recommended.
- rramadass 5y agoDo you mean this? 1) Write CPP macro language to emulate Oberon syntax. 2) Write program in the above macro language. 3) This program looks like Oberon but we now have two ways of "compiling" it; a) Feeding it to the CPP/C Compiler or b) Feeding it to the Oberon compiler directly with a little bit of tweaking. Have i understood it correctly?
- Koshkin 5y agoYes, you have.
- kajal7052 5y ago
- gmiller123456 5y agoBack when I had just learned Pascal, and was beginning to learn C, I did some of this. No idea why I thought that would make it easier to learn. I did not take it as far as the author of this article did. But I did expand it to function calls like "#define writeln printf". Looking back, I'm a bit amazed I managed to learn it, as I was obviously putting more work into not learning C than learning it.
- deleted 5y ago[deleted]
- vidarh 5y agoIt was practically a rite of passage back in the days when Pascal and Pascal-like languages were common to do this with C....
- rramadass 5y agoCheckout this Arthur Whitney (Genius Language Designer/Programmer) thread - https://news.ycombinator.com/item?id=19481505 https://news.ycombinator.com/item?id=19481505 In the above thread, user "yiyus" actually went through the macro code line-by-line and made explanatory notes; unbelievable! - https://docs.google.com/document/d/1W83ME5JecI2hd5hAUqQ1BVF32wtCel8zxb7WPq-D4f8/edit https://docs.google.com/document/d/1W83ME5JecI2hd5hAUqQ1BVF3...
- whatsakandr 5y agoOnce I macro'd `const auto` to `let` in my C++ program. After a few moments of "haha C++ go rust", I got terrified and undid it.
- krupan 5y agolet is now a thing in C++, but not const auto, so probably good that you undid it :-)
- chx 5y agoThere was a reddit thread about crafty Unicode usage in programming a few years ago. https://www.reddit.com/r/rust/comments/5penft/parallelizing_enjarify_in_go_and_rust/dcsgk7n/ https://www.reddit.com/r/rust/comments/5penft/parallelizing_... > If you look closely, those aren't angle brackets, they're characters from the Canadian Aboriginal Syllabics block, which are allowed in Go identifiers. From Go's perspective, that's just one long identifier. The thread goes downhill fast from there to the point where > I once wrote a short Swift program with every identifier a different length chain of 0-width spaces.
- RegW 5y agoYep. Been there. Done that. In the 80's I worked for a guy who insisted that we wrote all our C using macros that made it look like FORTRAN, amongst much other nonsense. How fondly I remember the many hilarious hours spent trying to pin down the cause of unexpected results. I don't remember any specific examples, but consider: #define SQ(v) v*v int sq = SQ(++v);
- Too 5y agoClassic pitfall with any type of text based pre processor. All variables inside need excessive amount of parenthesis. In similar vein there is also the “do {} while 0” trick to allow macros to be appear like normal functions and end with semicolon. Don’t even want to imagine how many more hacks would be needed to transform into another syntax using macros only.
- kazinator 5y ago> Caught me. I had recently heard that Arthur Whitney, author of the A+, k, and q languages (which are array programming languages like APL and J), would use the C preprocessor to create his own language and then write the implementation of his language in that self-defined language. Stephen Bourne did this in the sources of the Bourne shell, around 1977, to make C look like Algol. Here it is in V6 Unix, 1979: https://www.tuhs.org/cgi-bin/utree.pl?file=V7/usr/src/cmd/sh/mac.h https://www.tuhs.org/cgi-bin/utree.pl?file=V7/usr/src/cmd/sh... https://www.tuhs.org/cgi-bin/utree.pl?file=V7/usr/src/cmd/sh/ https://www.tuhs.org/cgi-bin/utree.pl?file=V7/usr/src/cmd/sh...