10 ms·
Getting silly with C, part (void*)2
- sylware 2y agoC syntax is already way too rich and complex. We need a C- ore µC: No implicit cast except for literals and void* (explicit compile time/runtime casts), one loop statement (loop{}), no switch/enum/generic/_thread/typeof/etc, no integer promotion, only sized primitive types (u64 s32 f32 etc...), no anonymous code block, real compiler hard/compile time constant declaration, many operators have to go (--,++, a?b:c, etc)... and everything I am forgetting right now (the dangerous struct pack attribute...). But we need inline keywords for memory barriers, atomics for modern hardware architecture programming.
- short_sells_poo 2y agoSooo, assembly :)
- poincaredisk 2y agoNo. Assembly is not portable, not typed and not structured (as in structured programming). Another usecase for microC: most decompilers decompile to a custom C-like language. It pretends to be C, but in reality this is just a representation of a recovered AST that is often-but not always-a valid C code. MicroC would be a better target, because it would supposedly have less weird edge cases.
- deleted 2y ago[deleted]
- 9rx 2y ago> Assembly [...] not typed and not structured (as in structured programming). That depends on the assembly language. Some have structure constructs, some are typed. Portability is out. But if you accept a slightly higher abstraction, WebAssembly is portable, typed, and structured.
- PittleyDunkin 2y ago> But if you accept a slightly higher abstraction, WebAssembly is portable, typed, and structured. Does WebAssembly support AOT compilation to native binaries? I thought it was just a VM.
- 9rx 2y agoIt does if you implement it! You can do anything if you get around to doing it. Or use an existing implement like wasmedge, I guess.
- deleted 2y ago[deleted]
- jcranmer 2y agoI'd argue that unsafe Rust is a better target here (although I don't know if &raw has made it into stable Rust yet, which you need for doing an address-of that doesn't have a risk of UB like & does). Rust's typesystem is less silly (there's only one multiple-types-for-same-value, namely usize), there's no implicit conversions, the core CFG primitives are a little bit richer (labeled break/continue, although those are now added in C2y), and there's a decent usable intrinsic class for common operators-not-in-C like rotations or popcount. If your goal is a simple language to compile, well, Rust won't ever fit the bill; but as a target for a decompiler, I think the unsafe subset is worth exploring.
- steveklabnik 2y ago&raw landed in the release just before this latest one. And even before that release, there were macros the poly fill it, so you could have used those to target an earlier version.
- uecker 2y agoWhy would you target a language that is less portable and less stable?
- jcranmer 2y agoFor the specific question of decompiling, as noted in the GP comment, you're already forced to decompile to a not-quite-C language because C's semantics just aren't conducive to accurately representing the hardware semantics. Not that Rust doesn't have its own foibles, but I suspect its core semantics are easier to map to than C's semantics without having to resort as much to a not-quite-Rust target. It's definitely something I would like to see at least explored!
- uecker 2y agoI am pretty sure somebody will do this. My guess is that it will make basically no difference, but the end result is likely less useful...
- 2y ago
- uecker 2y agoI don't think any weird edge case is a problem when targeting C. You just do not produce such cases when emitting the code.
- pjmlp 2y agoHence why Macro Assemblers have existed for almost as long as raw Assembly. MASM and TASM, were already far beyond the features in K&R C, if we overlook the issue of being bound to 80x86 Assembly. TI has some DSPs where their Assembly is basically bare bones C like, in a SSA kind of approach.
- Frenchgeek 2y agoSphinx C-- maybe?
- sylware 2y agoIs that microsoft C--?
- Frenchgeek 2y agohttps://bkhome.org/archive/goosee/cmm/ https://bkhome.org/archive/goosee/cmm/
- sylware 2y agoHad a look, its syntax is already too rich: I saw "while" "switch" etc. I guess, we are looking for even simpler thas sphinx c--. I start to wonder, if I could not express such simple C syntax using a powerful assembler macro preprocessor (like the one of fasm2). Until there is a "expression" processor, it should kind of be easier.
- sylware 2y agoYep, assembly... but a royalty free, brutally simple ISA... Wait... we have it... RISC-V. But we need performant µArchitectures of all major use cases (server/desktop/mobile/etc) and that on the best silicon process. If RISC-V is a success, no need for a µC, just go RISC-V assembly BUT... do not abuse that macro preprocessor, because if it is to move complexity from the C syntax to some macro preprocessor, that would be pointless.
- accelbred 2y agoDoes Zig fit your bill?
- sylware 2y agoDunno, I should have a look though. But I have recollection of some garbage collector, wrong/right ?
- nick__m 2y agoI doubt that, zig is allocators land. Even stdlib datastructures required an allocators to be instanciated. Have a look at the selection of allocators: https://zig.guide/standard-library/allocators https://zig.guide/standard-library/allocators .
- sylware 2y agoI had a look, zig seems to require a runtime, even small, for basic syntax support. So it seems it is not suitable. You should be able to generate machine code without the need of any runtime, like you can with C.
- mlugg 2y agoI'm unsure what you're referring to here -- Zig doesn't have any runtime, it doesn't even depend on libc. The only thing I can think of that you might be referring to is compiler-rt: if so, this is a thing in C too! It's just a small collection of implementations for operations the code generator wants to call into (e.g. memset, arithmetic for integers larger than CPU word size). Clang uses compiler-rt when compiling C code, and GCC's equivalent is libgcc. Nonetheless, Zig lets you disable it using `-fno-compiler-rt`, in which case you'll need to provide the relevant symbols yourself somehow.
- sylware 2y agoThis is not what I understood, there is some kind of flags required for pointers or something, which requires a data section for basic primitive types.
- glouwbug 2y agoC really just needs if / else / while / and void functions. Function inputs should be in/out (const type* or type*).
- bregma 2y agoSo, FORTRAN IV except for the else.
- mystified5016 2y agoYou want assembly with some sugar. Read up on Forth languages. It's pretty much exactly what you're after.
- mananaysiempre 2y agoForth is kind of weak dealing with value types of unknown size. For example, suppose you're writing a cross-compiler, and an address on the target machine might take one or two cells on the host machine depending on the host bitness. Now suppose you need to accept a (host-machine) cell and a target-machine address (e.g. an opcode and an immediate) and manipulate them a bit. Trivial in C, definitely possible in Forth, but supremely annoying and the elegance kind of falls apart.
- sylware 2y agoendian support is like the memory barrier and atomic support, should be inline function/keyword.
- mystified5016 2y agoAssembly isn't portable? Wow! You must be some type of genius! I'll start calling newspapers
- mananaysiempre 2y agoAssembly language isn’t, but assemblers usually are. If you want a (cross-)assembler for 32-bit x86, you can build GNU as or Nasm on any reasonable platform with a C implementation, because, ultimately, bytes are bytes, and you can write void emitd(struct buf *buf, int opcode, uint_least32_t address); or however it looks inside your assembler without caring what sizeof(int) is (assuming CHAR_BIT is 8). By comparison, in Forth that will be emitd ( buf op adr -- ) ( 32-bit host ) emitd ( buf op ahi alo -- ) ( 16-bit host ) depending on the bitness of where your assembler runs, even if the machine it assembles for is exactly the same in both cases. You cannot hide the platform difference behind a typedef for uint_least32_t or whatnot, unless you’re willing to drastically reshape the entirety of Forth from inside (which it does allow).
- butterisgood 2y agoPre-scheme?
- wongarsu 2y agoThere is C0, a stripped-down version of C popular in academia [1]. Great for teaching because it's conceptually simple and easy to write a compiler for. But with a couple of additions (like sized primitive types) it might match what you are imagining 1: https://c0.cs.cmu.edu/docs/c0-reference.pdf https://c0.cs.cmu.edu/docs/c0-reference.pdf
- GranPC 2y agoCan anyone explain how the last snippet works?
- a12k 2y agoBasically they execute in order of array initialization, not index order, so it outputs hello cruel world rather than cruel world hello.
- andreyv 2y agoIt creates a compound literal [1] of type array of int, and initializes the specified array positions using designated initializers [2] with the results of calls to puts(). Using designated initializers without the = symbol is an obsolete extension. [1] https://gcc.gnu.org/onlinedocs/gcc/Compound-Literals.html https://gcc.gnu.org/onlinedocs/gcc/Compound-Literals.html [2] https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html
- matheusmoreira 2y agoNote that this is GNU C, not standard C. GNU has extended the normal C language with features such as forward parameter declarations and numeric ranges in switch cases. Lots of people don't know about these things.
- dzaima 2y agoNote that switch case ranges might be coming in C2y though.
- mananaysiempre 2y agoAlso forward parameter declarations, or is that proposal dead?
- wahern 2y agoBasically dead. The main motivation would be to make it easier to use variably modified types in function parameters, where the (length) identifier is declared after the variably modified type, as in > void foo(int a[m][m], int m) Currently you can only do: > void foo(int m, int a[m][m]) The holy grail is being able to update the prototypes of functions like snprintf to something like: > int snprintf(char buf[bufsiz], size_t bufsiz, const char *, ...); However, array pointer decay means that foo above is actually: > void foo(int (*a)[m], int m) Likewise, the snprintf example above would be little different than the current definition. There's related syntax, like > foo (int m, int a[static m]) But a is still just a pointer, and while it can help some static analyzers to detect mismatched buffer size arguments at the call site, the extent of the analysis is very limited as decay semantics effectively prevent tracing the propagation of buffer sizes across call chains, even statically. There's no active proposal at the moment to make it possible to pass VM arrays (or rather, array references) directly to functions--you can only pass pointers to VM array types. That actually works (sizeof *a == sizeof (int) * m when declaring int (*a)[m] in the prototype), but the code in the function body becomes very stilted with all the syntactical dereferencing--and it's just syntactical as the same code is generated for a function parameter of `int (*a)[m]` as for `int *a` (underneath it's the same pointer value rather than an extra level of memory indirection). There are older proposals but they all lost steam because there aren't any existing implementation examples in any major production C compilers. Without that ability, the value of forward declarations is greatly diminished. Because passing VM array types to functions already requires significant refactoring, most of the WG14 felt it wasn't worth the risk of adopting GCC's syntax when everybody could (and should?) just start declaring size parameters before their respective buffer parameters in new code.
- deleted 2y ago[deleted]
- svilen_dobrev 2y agohehe. similar to How to Get Fired Using Switch Statements & Statement Expressions: https://blog.robertelder.org/switch-statements-statement-expressions/ https://blog.robertelder.org/switch-statements-statement-exp...
- kazinator 2y agoWithout information about how identifiers are declared, you do not know how to parse this: (A)(B); It could be a cast of B to type A, or function A being called with argument B. Or this (like the puts(puts) in the article): A(B): Could be a declaration of B as an identifier of type A, or a call to a function A with argument B. Back in 1999 I made a small C module called "sfx" (side effects) which parses and identifies C expressions that could plausibly contain side effects. This is one of the bits provided in a small collection called Kazlib. This can be used to make macros safer; it lets you write a #define macro that inserts an argument multiple times into the expansion. Such a macro could be unsafe if the argument has side effects. With this module, you can write the macro in such a way that it will catch the situation (albeit at run time!). It's like a valgrind for side effects in macros, so to speak. https://git.savannah.gnu.org/cgit/kazlib.git/tree/sfx.c https://git.savannah.gnu.org/cgit/kazlib.git/tree/sfx.c In the sfx.c module, there is a rudimentary C expression parser which has to work in the absence of declaration info. In other words it has to make sense of an input like (A)(B). I made it so that when the parser encounters an ambiguity, it will try parsing it both ways, using backtracking via exception handling (provided by except.c). When it hits a syntax error, it can backtrack to an earlier point and parse alternatively. Consider (A)(A+B). When we are looking at the left part (A), that could plausibly be a cast or declaration. In recursive descent mode, we are going left to right and looking at left derivations. If we parse it as a declaration, we will hit a syntax error on the +, because there is no such operator in the declarator grammar. So we backtrack and parse it as a cast expression, and then we are good. Hard to believe that was 26 years ago now. I think I was just on the verge of getting into Lisp. I see the sfx.c code assumes it would never deal with negative character values, so it cheerfully uses the <ctype.h> functions without a cast to unsigned char. It's a reasonable assumption there since the inputs under the intended use case would be expressions in the user's program, stringified by the preprocessor. Funny bytes would only occur in a multi-byte string literal (e.g. UTF-8). When I review code today, this kind of potential issue immediately stands out. The same exception module is (still?) used in the Ethereal/Wireshark packet capture and analysis tool. It's used to abort "dissecting" packets that are corrupt or truncated.
- utopcell 2y agoC[++] never ceases to amaze me. Just yesterday I saw this, totally valid, code snippet: void g(); void f() { return g(); }
- gpderetta 2y agoWhat's wrong with that?
- gizmo686 2y agoIn C function prototypes with no arguments are strange. void g(); Means that g is a function which takes a not-specified number of arguments (but not a variable number of arguments). Almost always what you want to do is void g(void) Which says that g takes 0 arguments. Having said that, declaring it as g() should work fine as long as you always provided that you always invoke it with the correct arguments. If you try invoking it with the wrong arguments, then the compiler will let you, and your program may just break in fun and exciting ways. Edit: looking closer, it looks like the intent might have been to alias f and g. But, as discussed above, it does so in a way that will break horribly if g expects any arguments.
- utopcell 2y agoWell, at the risk of stating the obvious: `return expr;` is meant to return whatever expr evaluates to. Here, g()'s return type is void, so there's no value to return and at the same time, f()'s return type is void, so return should not have an expr to begin with. This statement is effectively equivalent to: "g(); return;".
- deleted 2y ago[deleted]
- frizlab 2y agoso?
- josephg 2y ago> so return should not have an expr to begin with. Thats one way to think about it. Another is that void is a type - which is obviously true given you can have void* pointers and functions can return void. In this example, f() returns a void expression, so that’s a perfectly fine thing to return from g.
- jwilk 2y agoFirst part discussed on HN: https://news.ycombinator.com/item?id=40835274 https://news.ycombinator.com/item?id=40835274 (113 comments)
- psychoslave 2y agoUsually I'm more in the camp of "let's preserve everything we can as cultural heritage, yes even those awful Nazi propaganda material" and I'm confident that some distant archeologist (or current close neighbor) will be glad we did. But as time pass, I'm more and more convinced that wiping-out every peace of C that was ever produced would be one of the greatest possible gesture for the future of humanity. I also have a theory that universe exits so we can have some opportunities to taste chocolate. Surely in that perspective, even C can be an unfortunate but acceptable byproduct.
- adonovan 2y agoRemember that C's contemporary languages were either inefficient (e.g. ALGOL 68, PL/1, Lisp), functionally obsolete (e.g. FORTRAN didn't have recursion or heap allocation), or even lower level (Assembly, B). C eliminated the need for need for assembly in programs that were low level (like OS kernels) or high performance (math, graphics, signal processing), and that was surely a huge improvement in type safety and expressiveness.
- psychoslave 2y agoWell, Basic and Pascal was already something I guess, and Modula arrived in the same "era" as C. So at a general level the weight of C is to my mind not so much due to how it was shining out of the crowd of its alternative options for general programming. Instead my perception is that it's mostly due to a conjunction of where it was born (Bell Labs), its initial focus on construction of low level layer parts (kernel/OS), and how software stacks tends to leak. That doesn't void completely what C achieved at a technical level, of course. But it certainly ponder differently how much its spread can be weighted on its technical benefits.
- anticensor 2y agoYou missed one important category: too verbose (COBOL, Pascal).
- chasil 2y agoBut how interesting would your life become if SQLite ceased to function anywhere around you? Should this misfortune befall you, please don't get on an airplane (with me).
- mystified5016 2y agoForward parameter declaration is an insane feature. It makes perfect sense in the context of C's other forward declarations but just bonkers. I can't wait to slip this into some production code to confuse the hell out of some intern in a few years
- AKluge 2y agoAn old classic: Remember, C was never intended to be taken seriously. https://www.cs.cmu.edu/~jbruce/humor/unix_hoax.html https://www.cs.cmu.edu/~jbruce/humor/unix_hoax.html
- deleted 2y ago[deleted]
- rramadass 2y agoHa, Ha! Didn't know of this. Money quote; We stopped when we got a clean compile on the following syntax: for(;P("\n"),R-;P("|"))for(e=3DC;e-;P("_"+(u++/8)%2))P("|"+(u/4)%2); I am NOT going to try it out.
- GrantMoyer 2y agoI should keep this link handy for when people claim C is a simple language. Even without the GNU extensions, the examples here are pretty wretched.
- SAI_Peregrinus 2y agoC is a small language. People confuse simple with small quite often. As languages get smaller, using them gets more difficult once below a certain size. The "Turing tarpit" languages like Brainfuck are extremely difficult to write complex programs in, mostly because they're so small. C is clearly too small to be simple. C++ is too large to be simple. Somewhere in between, there may exist a simple language waiting to be invented.
- tpoacher 2y agoC is simple in the same way Conway's Game of Life is simple. That's not to say you can't create interesting monstrocities out of it!
- betimsl 2y agoWhere can I find more about this BASIC compatibility mode? Thnx
- hackyhacky 2y agoOf course it isn't really BASIC compatibility mode. In reality, it's an lesser-known array initialization syntax. It's explained here: https://jameshfisher.com/2016/12/25/c-array-literal-explicit-indexes/ https://jameshfisher.com/2016/12/25/c-array-literal-explicit... In short, you can initialize an array like this, by specifying each element in order: int foo[] = {10,20,30}; // initialize elements 0, 1, and 2 However, you can also initialize specific array elements: int foo[] = {[50] 10, [51] 20, [52] 30}; // initialize elements 50, 51, 52 "BASIC compatibility" mode uses the above syntax.
- betimsl 2y agoI never knew you can do this. Wow.
- mhandley 2y agoI expect many people know this one, but it's a useful teaching aid when understanding the relationship between arrays and pointers int array[10]; *(array+1) = 56; array[2] = 4; 3[array] = 27; The first two are obvious, but the third is also legal. It works because array indexing is just sugar for pointer arithmetic, so array[2]=4 is identical in meaning to *(array+2)=4. Therefore 3[array]=27 is identical to *(3+array)=27 and so is legal. But just because you can doesn't mean you should.
- macintux 2y agoThe best, most entertaining book I've ever read on C covered that (unless I'm misremembering, but I doubt it): Expert C Programming. https://www.goodreads.com/book/show/198207.Expert_C_Programming https://www.goodreads.com/book/show/198207.Expert_C_Programm...
- dualogy 2y agoI'm already liking that one! Page 5 quote: > There is one other convention — sometimes we repeat a key point to emphasize it. In addition, we sometimes repeat a key point to emphasize it. One more quote and I'll stop: > ctime() converts its argument into local time, which will vary from GMT, depending on where you are. California, where this book was written, is eight hours behind London, and several years ahead
- WalterBright 2y ago> The first two are obvious, but the third is also legal. D doesn't have that bug! In 44 years of C programming, I've never encountered a legitimate use for the 3rd. (Other than Obfuscated C, that is.))
- mhandley 2y agoAgreed - I've only been programming C for 38 years but I've also never found a legitimate use. However I have used it to illustrate a point when teaching C to beginners - it looks so odd they tend to remember it.
- 2y ago
- WalterBright 2y agoI'm going to speculate a bit on why these silly things are in C. C was developed on a PDP-11 that had 64Kb of memory. That's not much of any at all. Therefore, the compiler must be extremely tightly coded. The fundamental rules of the C language are pretty simple. But articles like these expose consequences of such simple rules. Fixing them requires adding more code. Adding more code means less room for the code being compiled. Therefore, if the intended use of the language works, the pragmatic approach would be to simply not worry about the quirky consequences. A more interesting question would be "why do these characteristics persist in modern C compilers?" The stock answer is "backwards compatibility", "Obfuscated C Code contests" and "gotcha job interview questions". My argument would be that there is no reason for the persistence of such "junk DNA" and it should be deprecated and removed. I've done my part. D doesn't support that stuff, even though the basic use of the language is easily confused with C. For example: #include <stdio.h> void main() { int i; for (i = 0; i < 10; ++i); printf("%d\n", i); } I've died on that hill. I know others who lost an entire day staring at it wondering what's wrong with it. I saw it on X recently as "99% of C programmers will not be able to find the bug." The equivalent D code: import core.stdc.stdio; void main() { int i; for (i = 0; i < 10; ++i); printf("%d\n", i); } gets you: test.d(5): Error: use `{ }` for an empty statement, not `;` C'mon, Standard C! Fix that!
- HeliumHydride 2y agoI was able to find it instantly, but that's because I always use curly braces for my if/while/for loops.
- WalterBright 2y agoI added a warning for it in my C compiler back in the mid 1980s. Fun story. A friend of mine (Eric Engstrom!) bought himself a backhoe. I'd never driven one before and he offered to let me drive it. Sure! The clutch pedal works backwards from that in a car. Press on the clutch to engage it, release the pedal to disengage it. After some struggling with my reflexes being all wrong, I came within a couple feet of taking out the side of his barn - by switching off the key. There was nothing wrong with that user interface, other than being insane.
- zzo38computer 2y agoI had read the GCC documentation and I did not know about the forward parameter declaration. I did know about the other stuff that is mentioned there (and in the first part). Declarations in for loops is something that I had only ever used in macros (I had not found it useful in other circumstances), such as: #define lpt_document() for(int lpt_document_=lpt_begin();lpt_document_;lpt_document_=(lpt_end(),0)) #define win_form(xxx) for(win_memo win_mem=win_begin_();;win_step_(&win_mem,xxx)) (The compiler will optimize out the loop and the declared variable in the use of the lpt_document macro; I had tested this.)
- teddyh 2y agoThe comp.lang.c Frequently Asked Questions <https://c-faq.com/ https://c-faq.com/> should be required reading for every serious C programmer.
- hulitu 2y agoAlso the C infrequently asked questions https://www.seebs.net/faqs/c-iaq.html https://www.seebs.net/faqs/c-iaq.html
- dfawcus 2y agoI'd have to argue the function typedefs are not useless, I've come across two uses. The obvious one is rather than a function pointer typedef, such the subsequent use in a struct is obviously a pointer. Which helps when others are initially reading unfamiliar structures. typedef int handler_ty(int a); struct foo { handler_ty *handler; /* ... */ } struct foo table[] = { { /* init fields */, /* init fields */, }; The other case can be somewhat related, namely as an assertion / check when writing such handler functions, and more importantly updating them. handler_ty some_handler; int some_handler(int a) { /* ... */ } When updating code, it allowed for easier to decode compiler errors if the expected type of handler_ty was changed, and some specific handler was incorrectly updated, or not updated at all. Basically the error would generally directly call out the inconsistency with the prior line, rather than with the distanct use in the initialisation of 'table'. As I recall this mechanism has been around since at least C89, I don't recall using it in K&R.