21 ms·
Some Obscure C Features
- jimmoores 7y agoThese examples actually were more obscure than the usual list.
- pickdenis 7y agoThe multiple compatible function signature declaration got me. I pray that I'll never have to understand and work with code that looks like that.
- deleted 7y ago[deleted]
- dkersten 7y agoYeah, I did know 3 of them[1] but the rest were completely new to me! Not that I’m an expert or anything, but I tend to enjoy reading about obscure C features. That sizeof can have side effects is... a bit crazy although the multiple compatible function declarations are horrifying. [1] Array designators, Preprocessor is a functional language and a[b] is a syntactic sugar.
- Sharlin 7y agoAmusingly enough, that’s because most of them are C99 features.
- deleted 7y ago[deleted]
- bsder 7y agoAlthough calling the preprocessor "functional" is being too pleasant. The C preprocessor was always a text substitution system, so macro as parameter is not that "obscure". Of course, I may have missed something subtle in the example. It's also not clear how to use that preprocessor example.
- elteto 7y agoIt can be very useful! I added a small comment with an example of how I used it once.
- augusto-moura 7y agosee http://conal.net/blog/posts/the-c-language-is-purely-functional http://conal.net/blog/posts/the-c-language-is-purely-functio... old but gold
- juped 7y ago>The C ADT is implemented simply as String (or char *, for you type theorists, using a notation from Kleene) Still makes me laugh
- multun 7y agoIt is never obscure when you know it. And sure, it was always meant that way. It's just rarely used this way, which is why it's in this list. Here's what the example yields once preprocessed: struct operator{ int priority; const char *value; }; struct operator operator_negate = { .priority = 20, .value = "!", }; struct operator operator_different = { .priority = 70, .value = "!=", }; struct operator operator_mod = { .priority = 30, .value = "%", };
- jcranmer 7y agosizeof actually doesn't evaluate its expression for side effects most of the time; only if the operand is a variable-length array is it evaluated.
- saagarjha 7y agoAnother reason why VLAs are considered anathema in many projects.
- _kst_ 7y agoAnd it's not even entirely clear what that means. The standard says: "If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant." But what does it mean to evaluate the operand? If the operand is the name of an object: int vla[n]; sizeof n; what does it mean to evaluate `n`? Logically, evaluating it should access the values of its elements (since there's no array-to-pointer conversion in this context), but that's obviously not what was intended. And what about this: sizeof (int[n]) What does it mean to "evaluate" a type name? It's not much of a problem in practice, but it's difficult to come up with a consistent interpretation of the wording in the standard.
- jcranmer 7y ago> If the operand is the name of an object [...] what does it mean to evaluate `n`? When you say "n", syntactically, you have a primary expression that is an identifier. So you follow the rules for evaluating an identifier, which will produce the value. C doesn't describe it very well, but the value of the expression is the value of the object. In terms of how it is implemented in actual compilers, this would mean issuing a load of the memory location, which is dead unless `n` is a volatile variable.
- _kst_ 7y agoSorry, in the first example I meant to write (adding a declaration and initialization for n): int n = 42; int vla[n]; sizeof vla; not `sizeof n`). (It doesn't look like I can edit a comment.) Logically, evaluating the expression `vla` would mean reading the contents of the array object, which means reading the value of each of its elements. But there's clearly no need to do that to determine its size -- and if you actually did that, you'd have undefined behavior since the elements are uninitialized. (There are very few cases where the value of an array object is evaluated, since in most cases an array expression is implicitly converted to a pointer expression.) In fact the declaration `int vla[n];` will cause the compiler to create an anonymous object, associated with the array type, initialized to `n` or `n * sizeof (int)`. Evaluating `sizeof vla` only requires reading that anonymous object, not reading the array object. The problem is that the standard doesn't express this clearly or correctly.
- EGreg 7y agoHere is an obscure c feature: int main() { int a = 8; { int a = 4; /* a is only scoped to this block */ } printf("%d", a); /* prints 8 */ } It is also why C++ is not a strict superset of C
- dkersten 7y ago> It is also why C++ is not a strict superset of C Can you explain? That code in C++ also scopes ‘a’ to the block. EDIT: I see you’ve edited the code, but I think it’s still true in C++. I’ve often done that for RAII and unless I’m mistaken it works just as well when shadowing variables like you’re doing as when not.
- scott_s 7y agoAgreed. And I have also used it in C++ for RAII purposes. In C++, braces introduce a scope, and objects local to that scope will be destructed upon exit.
- scott_s 7y agoThat's true in C++ as well: https://en.cppreference.com/w/cpp/language/scope https://en.cppreference.com/w/cpp/language/scope
- eMSF 7y agoThat's hardly obscure: it's Javascript that's the odd one out of the languages with C-like syntax, with its wacky function-level scoping instead of variable shadowing when using 'var', and falling back to global scope when not declaring a variable properly. Also, C and C++ behave identically with your given example. A perhaps obscure feature is that you can "unshadow" a global variable like this: #include <stdio.h> int global = 0; int main() { int global = 1; { extern int global; printf("%d\n", global); // prints 0 } }
- truncate 7y agoI don't think that's obscure at all. That's standard lexical scoping. Do it all the time in functional languages.
- elteto 7y agoThe preprocessor trick of passing function macros as parameters is not that obscure. I have seen it used and I've used it myself. It is very useful when you have a list of static "things" that you need to operate on. Say I have a static list of names and I would like to declare some struct type for each name. I also would like to create variables of these structs at some point, and I would always do so for the entire block of names. You could do something like this: #define apply(fn) \ fn(name1) \ fn(name2) \ fn(name3) \ ... fn(nameN) #define make_struct(name) struct name##_t { ... } #define make_variable_of(name) name##_t name; ... apply(make_struct); // This defines all the structs. void some_function(...) { apply(make_variable_of); // And this defines one variable of each type. } Yes, it is not pretty (it is the C preprocessor after all), but it can be very useful and clean.
- jcranmer 7y agoI'd say none of the preprocessor stuff on this list is obscure--I've seen all of them in projects before.
- kzrdude 7y agoI would call that the X macro pattern, but the wiki article doesn't agree that it should pass the `fn` as the argument. Not sure if that's important.. https://en.wikipedia.org/wiki/X_Macro https://en.wikipedia.org/wiki/X_Macro
- elteto 7y agoMaybe at some point macros could not be passed as arguments? I honestly don’t know. Passing it as a parameter avoids all that define/undefine business.
- multun 7y agoIt can be both useful and obscure ;-) I realize it's not black magic, it's just uncommon. I used this trick to declare and generate code for an entire parser, it's lovely. I recently switched to the other style of C-macro though: #define X(A, B, C) ... #include <math/apply_operators.h> #undef X This style is less powerful but doesn't require the annoying \ at the end of lines.
- conistonwater 7y agoIn numerical analysis, "Hexadecimal float with an exponent" is not an obscure feature, it's a really nice one! If you want to communicate to somebody an exact number that your program has output, you need to either tell them the decimal number to enough digits + the number of digits (i.e., "Float32(0.1)", which is distinct from "Float64(0.1)"), or you can tell them the same number in full precision in binary, in which case the floating-point standard guarantees that that number is exactly correct and does not depend on how you interpret it. It's really nice for testing numerical code, especially with automated reproducible tests. Completely unambiguous, and I wish more languages had that (I saw the feature in Julia first).
- piadodjanho 7y agoAlso, the printf can be used to display floating point in hexadecimal notation. The printf specifiers: %e Scientific notation 3.9265e+2 %a Hexadecimal floating point -0xc.90fep-2
- jacobolus 7y agoI wish Javascript, etc. had hexadecimal floats. It’s annoying to worry about whether different implementations might parse your numbers differently, worrying about whether you need to write down 15 or 17 decimal digits, ... Often the numbers (e.g. coefficients of some degree 10 polynomial approximation of a special function) are not intended to be human-readable anyway. Such values were typically computed in binary in the first place, and the only place they ever need to be decimal is when written into the code, where they will be immediately reconverted to binary numbers for use.
- microcolonel 7y agoI mean, it's not too difficult to add them. You can parse, shove your result into a data view, Uint32Array, or whatever, then turn that into a Float64Array.
- jacobolus 7y agoFair enough. You can also just base64-encode (or whatever) a big block of binary data. But having built-in support for hex floats would be nicer.
- haolez 7y ago> a[b] is literally equivalent to *(a + b). You can thus write some absolute madness such as 41[yourarray + 1]. Wow. This has to be the best C obscurity that I've ever seen.
- ChuckNorris89 7y agoAs an embedded dev, I didn't know these things were actually obscure. Granted, we never used such things in production.
- _kst_ 7y agohttps://stackoverflow.com/q/381542/827263 https://stackoverflow.com/q/381542/827263 https://stackoverflow.com/a/18393343/827263 https://stackoverflow.com/a/18393343/827263
- multun 7y agoCome on, that might not be obscure for a C ninja master like you, but I'm pretty sure many people had no idea ;-) Notice how the list is sorted from actually obscure to less interesting. I even took the time to write a pseudo disclaimer above this one :D
- haolez 7y agoI wasn't being ironic :)
- deleted 7y ago[deleted]
- deleted 7y ago[deleted]
- kazinator 7y agoMost of these are due to the cruft added in C99 and later. Compile-time trees are possible without compound literals. More than twenty years ago, I made a hyper-linked help screen system a GUI app whose content was all statically declared C structures with pointers to each other. At file scope, you can make circular structures, thanks to tentative definitions, which can forward-declare the existence of a name, whose initializer can be given later. Here is a compile-time circular list struct foo { struct foo *prev, *next; }; struct foo n1, n2; /* C90 "tentative definition" */ struct foo circ_head = { &n2, &n1 }; struct foo n1 = { &circ_head, &n2 }; struct foo n2 = { &n2, &circ_head }; You can't do this purely declaratively in a block scope, because the tentative definition mechanism is lacking. About macros used for include headers, those can be evil. A few years ago I had this: #include ALLOCA_H /* config system decides header name */ Broke on Musl. Why? ALLOCA_H expanded to <alloca.h>. But unlike a hard-coded #include <alloca.h>, this <alloca.h> is just a token sequence that is itself scanned for more macro replacements: it consists of the tokens {<}{alloca}{.}{h}{>}. The <stdlib.h> on Musl defines an alloca macro (an object-like one, not function-like such as #define alloca __builtin_alloca), and that got replaced inside <alloca.h>, resulting in a garbage header name.
- multun 7y agoOops I'm wrong, I meant compile time anonymous trees. It's very obviously possible by defining other variables.
- piadodjanho 7y agoAlso variable assignment with identifier list: a = 0; x = (type_t) { .y = a++, .x = a++ } Now, figure it out the order of the field's assignment.
- kazinator 7y agoThe order of evaluation among initializers is unspecified, which makes it UB. We don't have to use mixed-up designated initializers to run aground. Just simply: { int a = 0; int x[2] = { a++, a++ }; } This was also new in C99 (not to mention the struct literal syntax); in C90, run-time values couldn't be used for initializing aggregate members, so the issue wouldn't arise. Code like: { int a = 0; struct foo f = { a, a }; } was supported in the GNU C dialect of C90 before C99 and of course is also a long-time C++ feature. https://gcc.gnu.org/onlinedocs/gcc/Initializers.html#Initializers https://gcc.gnu.org/onlinedocs/gcc/Initializers.html#Initial... The doc doesn't say anything about order. I can't remember what C++ has to say about this.
- stefan_ 7y agoA nice but I guess more of a linker feature is if you declare a function as __weak__, you can check it at runtime for == NULL to determine if the application was built with the function defined.
- _kst_ 7y agoThat's non-standard.
- multun 7y agoI would say most interesting linker features are non standard, so outside of the scope of this article :/
- cryptonector 7y agoTrue, however, it is precisely the stupid linker tricks that make C such an interesting and powerful language nowadays. Weak symbols. Interposition (LD_PRELOAD). dlopen() and friends. Filters. Direct binding / versioned symbols. ELF semantics in general (which make the use of one flat symbol namespace safer).
- shift_reset 7y agoThe article has examples of array parameters like int b[const 42][24][*] but you can get more fun with variably modified array parameters instead of just constants like 42. For example, double sum_a_weird_shaped_matrix(int n, double array[n][3*n]) { double total = 0; for (int x = 0; x < n; ++x) { for (int y = 0; y < 3 * n; ++y) { total += array[x][y]; } } return total; } has a variable and a more complicated expression in those positions. But those variably modified parameters can have arbitrary expressions in them, like int last(size_t len, int array[restrict static (printf("getting the last element of an array of %zu ints\n", len), len--)]) { return array[len]; } C++ denies us this particular joy which could have made function overload resolution even more fun.
- multun 7y agoI took the code sample of the article from a snippet intended to be as dirty as possible, and removed most madness out of it. But yeah you're right :D I just wanted to avoid adding one more item in that bullet list.
- stevenhuang 7y agoAnother neat note IIRC is that array parameter sizes don't actually do anything, they just are there for semantic purposes and get treated as raw pointers. So if you do void func(int x[10]); You're free to call it like int k[5]; func(k); And you won't get any warnings. Unsettling!
- shift_reset 7y agoThat's what the static keyword means in those array declarators. void func(int x[static 10]); must be called with an argument that is a pointer to the start of a big enough array of int. I can't get recent GCC or Clang to warn on violations of this, though.
- spc476 7y agoThere are cases where the compiler can't enforce it: void foo(int *p) { func(p); } How can the compiler know if `p` points to space for 10 integers?
- deleted 7y ago[deleted]
- nothis 7y agoAll craziness but then: >a[b] is literally equivalent to *(a + b). Is this obscure? I thought that's pretty much the first thing you learn about arrays in C? It's pointers, all the way down.
- saagarjha 7y agoIt's syntactic sugar that's more poorly abstracted than most people realize.
- arcticbull 7y agoAgreed, and I never made the connection that array[index] could be written as index[array] haha.
- anticensor 7y agoOnly if index and array have the types of same size. Because pointer arithmetic works in terms of object sizes, not in individual bytes.
- erik_seaberg 7y agofoo[3] *(foo + 3) *(3 + foo) 3[foo] They all do the same thing.
- arcticbull 7y agoInteresting! I assume because the literal is being coerced to be the size of the variable? After all: foo[3] == (void *)((usize)foo + (usize)(3 * sizeof(*foo)))
- erik_seaberg 7y agoYeah, that's how pointer arithmetic works. Adding an int and a pointer assumes an array and gives you a pointer to the nth element in that direction (which had better exist, for your sake). char pointers can be used for byte offsets if a byte is a char on your platform (and it's been quite a while since that wasn't true). You can also subtract two pointers into the same array and get the distance (in elements, not bytes). a[b - a] == b.
- radamadah 7y agoAre we calling these features, now?
- aspaceman 7y agoMost of the examples listed (hex floats especially) are very much features.
- needs 7y agoA little off-topic but here is a cool piece of code about a special case in C: void (*foo)() = 0; void (*bar)() = (void *)0; void (*baz)() = (void *)(void *)0; // Error Can you guess why compilers reject the last line?
- icedchai 7y agoMost modern compilers don't even warn about the last line unless you're in pedantic mode.
- eMSF 7y agoOnly the first two expressions on the right are null pointer constants (integral constant expression with a value of 0, optionally cast as a void *), that can be used to initialize all pointer variables, including function pointers. The last one is merely a null pointer (to void), that can't be implicitly converted to a pointer to a function. C++ has stricter rules for null pointer constants, and thus only the first version is valid C++.
- deleted 7y ago[deleted]
- piadodjanho 7y agoA more obscure feature is the uncommon usage of comma operator. We often use the comma operator in variable declaration and in for loops. But it can also be used in any expression. For instance, the next line has a valid C construct: return a, b, c; This is particularly useful for setting variable when retuning after an error. if (ret = io(x)) return errno = 10, -1; The possibilities are endless. Another example: if (x = 1, y = 2, x < 3) ... But the comma operator really shines when used in conjunction with macros.
- jakear 7y agoThe comma operator isn’t very obscure at all. Even JS has it.
- kbenson 7y agoIt's not the comma operator that is being noted as obscure, but particular usage of it, such as complex return statements that set a value and return another.
- jakear 7y agoRight, that’s also the case for comma in JS.
- piadodjanho 7y agoI reckon that most language with grammar inspired in C describes the comma operator.
- kbenson 7y agoSo, are you making the case that the examples present are common in JS as well? Because the whole point of the comment was in the uncommon usage of comma operator, as stated in the first sentence. And to be clear, even if it is common in JS, that still doesn't reduce the usefulness of the original comment, because we aren't talking about JS, we're talking about C, and the commonness of the features notes in the C ecosystem. There are plenty of obscure oft-ignored features on one language that are common in another. For example, taking someone's interesting C macro that allows some level of equivalence to functional map and apply and saying "that isn't very obscure, even lisp has that" is missing the point.
- etaioinshrdlu 7y agoI found the most interesting one to be compile time trees. Does anyone have any good use cases for it?
- saagarjha 7y agoA hardcoded trie for string matching, perhaps?
- lasagnaphil 7y agoMaybe for making a declarative GUI system in C? I’ve never seen this before, so I’m not sure it could be done.
- kccqzy 7y agoI don't like to think of it as compile-time trees. It basically only allows you to construct complicated structures but doesn't allow you to examine them at compile time (that would require constexpr functions in C++; can't be done in C). It's honestly not a very impressive feature.
- multun 7y agoI used it to describe neural network architectures.
- megous 7y agoLook at clk driver code for sunxi in mainline kernel. That uses it a lot. https://elixir.bootlin.com/linux/latest/source/drivers/clk/sunxi-ng/ccu_nkmp.h https://elixir.bootlin.com/linux/latest/source/drivers/clk/s...
- megiddo 7y agoHell, c11 has ghetto generics.
- compi 7y agoI was reading the source code for a NES assembler written in pre-C99 C, and there was an odd C feature used in it that I haven't really seen anywhere else. It was before C had built-in booleans and the author had defined their own, but true was: void * true_ptr = &true_ptr; true_ptr is a pointer to itself. So however many times you deference it: printf("%p\n", true_ptr); printf("%p\n", &true_ptr); printf("%p\n", *((void**)true_ptr)); printf("%p\n", *((void**)*((void**)true_ptr))); You get the same pointer: 0x5555fefe715b 0x5555fefe715b 0x5555fefe715b 0x5555fefe715b I still think that it's neat that, even with ASLR, you have an address at compile time that you know won't collide with address space of malloc results, or the address space of your stack. Also you can declare the pointer as const and the value it points to as const and, if your kernel faults on writing to readonly memory pages, you get a buggier version of a NULL pointer that only segfaults on write. Also it takes a second to figure out why the position of the const matters even though the pointer's value is the value of the pointer, and why only one of these segfaults on write: const void * const_pointer = &const_pointer; void * const const_value = &const_value;
- davelee 7y agoI've used this feature to create constants that are unique IDs.
- cryptonector 7y agocdecl> explain const void * const_pointer declare const_pointer as pointer to const void cdecl> explain void * const const_value declare const_value as const pointer to void cdecl> The first must be the one that segfaults on write, IFF the compiler chooses to place it in the .text (as it should).
- higherkinded 7y agoEffectful sizeof, what a delightful feature! Though the compile-time magic with structs and functional macros are so tempting that I feel like it's high time to do some C.
- inlined 7y agoThe WTF part seems useful. E.g. type quaternion float[4]; quaternion SLERP = {1.0, 0, 0, 0};
- kccqzy 7y agoDid you mean typedef float quaternion[4]; ? That's not a VLA.
- vq 7y agoNo mention of trigraphs? They are one of my favourite obscure C language features that I've never used. Excerpt from GCC man page: Trigraph: ??( ??) ??< ??> ??= ??/ ??' ??! ??- Replacement: [ ] { } # \ ^ | ~ Missing backslash on your keyboard? No problem, just type ??/ instead.
- MawKKe 7y agoMore than once have I written something like this if(condition) printf("WTF??! value: %d", value); ...only to have the compiler nag me about it. That's pretty much the only situation I've come across trigraphs :)
- goatinaboat 7y agoIIRC these are a legacy of BCPL
- pdw 7y agoThe story I heard was that the trigraphs were added during standardization because ISO 646, the international version of ASCII, did not require the characters [ \ ] { | }. Fun fact: ISO 646 is also the reason that IRC allows these characters in nicknames. IRC was created in Finland, and the Finnish national standard had placed the letters Ä Ö Å ä ö å at those code points. Edit: That doesn't explain the trigraphs for # ^ ~. I'm guessing some EBCDIC variants lacked those. Or some other computer vendor on the committee still supported some other legacy character set.
- jandrese 7y agoI had to use them once on a truly ancient amber screen serial terminal that lacked { and } on the keyboard. That was back in the 90s and the terminal was completely obsolete at the time but I needed to write a tiny hack program to solve an immediate problem. I remember only knowing about them in the first place from an odd compiler warning I'd seen on a different program.
- CarlRJ 7y ago
- real-ycomb 7y agoSsaaa1aaaaaaaaawaawawsßaSAA
- deleted 7y ago[deleted]
- Keyframe 7y agoOne of the more obscure, yet often employed, "features" is to use something else as a C preprocessor.
- JeromeLon 7y agoNo mention of the downto (-->) operator? int x = 10; while (x --> 0) { printf("%d ", x); }
- deckar01 7y ago> VLA typedef ... I have no clue how this could ever be useful. I used this feature recently. I had several arrays of the same size and type, and the size was determined at runtime. The VLA typedef let me avoid duplicate type signatures which I find more readable. int N = atoi(argv[1]); typedef int grid[N][N]; grid board; grid best; grid cache;
- tasty_freeze 7y agoThis was c++ and not C, but it is a preprocessor pitfall. I needed to compare and older and newer version of some file from the RCS, so I saved temporary copies named "new" and "old". diff told me what I needed to know, but I failed to delete those temp files. Hours later I typed "make" to build my program and got all sorts of errors deeply nested in some library function. Did someone misconfigure the server I was on? OK, maybe it is an incremental build problem? etc. It took took long to figure out the problem. It turns out that during compilation, as one of the library .h files was being scanned, it contained #include <new>, which picked up the junk file in my working directory instead of using the C library.