I think C's apparent simplicity lulls me into complacency at times, I delude myself into thinking that I'm coding into some kind of macro assembly and I think I know what the resulting machine code will look like. And then some super weird optimization or UB kicks in and nothing makes sense anymore, because I stopped playing by the rules and I triggered the footgun.
Just look at the number of bug reports on the GCC bugtracker for code that at a glance ought to work and it turns out that it's actually not a bug, the code just triggered a subtle UB and the compiler ran away with it and generated code that ate your cat.
I don't see the point of your claim regarding undefined behaviour. The rules are quite simple: undefined behavior means compiler-specific behavior. Therefore, if you aim for compiler independence then you don't use it. If somehou you decide yo target a compiler then you read the compiler's docs. It's that simple.
These UB complains are even more ridiculous when we realize they complain about the fact that the language is actually defined.
I think the point was that UB occurs in a lot of relatively common cases and programmers don't realize that they're depending on it/experiencing it.
> If [somehow] you decide [to] target a compiler then you read the compiler's docs.
Which is why the post you're responding to made the point about undefined behavior. "Read the compiler's docs" is in counterpoint to that post's parent, which praises C for being a small language, and thus one in which reading the language's docs is seldom required.
There are "implementation defined" details in the C standard but it's a different problem, see for instance: https://gcc.gnu.org/onlinedocs/gcc/C-Implementation.html
Anyway that wasn't really my point, the problem is that some of these UB can arise because of subtle bugs in code that might not look suspicious at a glance. Things like breaking aliasing rules, mis-using unions, casting things that aren't compatible etc... Your code triggers an UB and you don't know it. Actually you might not notice it until you turn an optimization flag or you update your compiler and suddenly it doesn't do what you want anymore.
Even something as trivial as computing a pointer that's more than one byte after the end of an object is UB for instance (not dereferencing it, merely computing its address). For that reason `ptr.offset` in unsafe in Rust for instance, even though it doesn't dereference the pointer.
fn main() {
// Look, an invalid pointer, no `unsafe` required.
let ptr = 1000 as *const u8;
// boom, segfault.
println!("{}", unsafe { *ptr });
}
Using casting one can even implement a "safe" pointer offset function, like so: fn main() {
fn safe_offset<T>(ptr: *const T, offset: isize) -> *const T {
((ptr as usize).wrapping_add(offset as usize)) as *const T
}
let xs = [0u8, 10];
let ptr = safe_offset(&xs[0], 1);
println!("{}", unsafe { *ptr }); // prints '10'
}
Obviously this "safe_offset" function can easily be used to trigger UB by computing invalid pointers, and not a single line of unsafe code was required (although we do need `unsafe` to dereference the bad pointer and actually trigger segfaults).>When casting from pointer to integer and back again, the resulting pointer must reference the same object as the original pointer, otherwise the behavior is undefined. That is, one may not use integer arithmetic to avoid the undefined behavior of pointer arithmetic as proscribed in C99 and C11 6.5.6/8.
https://gcc.gnu.org/onlinedocs/gcc/Arrays-and-pointers-imple...
That's pretty explicitly what Thiez was doing in their rust code, although obviously Rust/LLVM might have different semantics here.
I could be wrong but I think the above poster hasn't actually written tons of C, or else they would have picked a much more complicated example. If you throw a bunch of arrays, pointers, and function pointers in it quickly gets out of hand, like this:
int (* const(*foo)(int (*)(int, int))[5])(void);
That thing defines 'foo', which is a pointer to a function who's first argument is a pointer to a function return a int and taking two ints as arguments, and returns a pointer to an array of 5 const function pointers which take no arguments and return an int.Thankfully, you rarely run into something like that in the wild. And if you `typedef` the function pointers (Which is a pretty common now) it becomes tons easier to read.
I find this much easier to understand than something with different keywords and qualifiers. Function pointers follow some simple rules to read, but can you be sure of what `volatile` implies ?
Hmm, I suppose we just disagree then, which is fine. Things like `restrict` and `volatile` don't really bother me because:
1. The spots where people actually need to use them are very rare (`restrict` does have uses, but almost nobody uses it commonly. `volatile` has pretty much no correct uses outside of accessing registers in low-level code).
2. It's still just a pointer to a long long. I would need to look-up what __declspec((dllimport)) does, and I'd be highly suspicious of the use of `restrict` and `volatile` if it was not explained, but I still generally know what it is and how it can be used. Whereas with the example I gave, without staring for a long time or throwing it into a parser I can hardly tell what the type even is, let alone wrap my head around how it will be used.
Sorry, but what are you guys on about? You use "volatile" if you don't want the compiler to produce code that caches a variable. You use it all the time in embedded systems, or when writing multi-threaded code, etc. The usage of "volatile" is very clear, and should be well understood. "restrict" isn't used much because it's a c99 standard first of all, and second of all, it's like "inline"; it might make a difference, might not, and not a lot of people are in a situation where they have to shave off cycles.
Thanks for providing a very nice exhibit of the confusion around this. Volatile is 99% useless for multithreading code (unless on MSVC which has a peculiar interpretation of the standard). See https://stackoverflow.com/a/4558031/1495627
No amount of fences or mutexes is going to help you if threads are operating on their own version of a variable that got cached in a register, or optimised away. You need to understand volatile to write correct multi-threaded code.
That StackOverflow answer is bogus, along with all the other comments. It's just a rant that, albeit correct, is barely related to the question asked, and it's a clear example why you shouldn't treat StackOverflow as more than an unreliable help forum. The guy asked about whether you should make variables shared inside of a critical section volatile. The answer is "yes, to prevent threads from working on stale data".
Any properly written Mutex or similar implementation is going to act as a full memory barrier and compiler barrier, meaning variables will already not be cached across lock/unlock. And if you're not properly taking your locks before accessing your variables, `volatile` is not going to save you. The fact is, if you're using a lock to protect a variable, marking it `volatile` gains you nothing and just slows your code down.
> "yes, to prevent threads from working on stale data".
`volatile` absolutely does not guarantee a variable doesn't contain 'stale' data. That's the entire reason you need memory barriers in the first place. Even through the compiler will read a `volatile` variable from memory every time, that memory may still have a stale value in the CPU cache, which `volatile` will do nothing to prevent. Only proper use of memory barriers ensures everyone is working on the same thing, which `volatile` does not do.
Yes, it will! Just because you’re accessing shared variables doesn’t mean you need locks. This is what volatile is for!
You’re blindly hoping the compiler will do the right thing for you, anyway. You must have little-to-no experience writing multi-theaded code in production, let alone anything more advanced that doesn’t rely on locks.
Nobody’s arguing that volatile somehow bypasses the cache. When it comes to multithreading, that doesn’t matter though, because the whole process works with the cache, and the CPU keeps core caches synchronized. Memory barriers do nothing here.
Seriously, you’re arguing rubbish.
FWIW, it doesn't even do this, it's just a compiler-level annotation:
volatile int x = 0;
int foo() {
// read
int ret = x;
(void)x;
// write
x = 0;
x = 1;
return ret;
}
The 'volatile' ensures that that code results in two reads and two writes. Removing it allows the compiler to optimise down to the equivalent of 'int ret = x; x = 1; return ret;', but both with and without use the exact same read/write instructions (i.e. have the same interaction with the cache): mov on x86 and ldr/str on ARM.volatile's one of the simplest modifiers to understand if you care to actually learn the language. It has a clear, and well-defined purpouse, and i have no idea how you can spend so much time, and energy arguing that that's not the case.
None of it makes the language inherently any more complex, any more than representing machine instructions by long strings of binary makes _them_ any more complex.
With a boatload of associated semantics, quite a bunch bein in practice compiler-dependent (looking at you, MSVC volatile).
And a "protected abstract virtual base pure virtual private destructor" does not mean anything -- or at least any code that compiles.
Which is not part of C. Your argument that "C is complicated" doesn't work if you cite an egregious misuse of nonstandard extensions.
What about the zinger, “if you think English is not overly complex, just what is a loud old fast tall red car, and when was the last time you needed one?” No language I’m familiar with limits the number of adjectives you can use for a single noun. That doesn’t mean you generally should string several adjectives together; usually you’re fine just saying “car,” but sometimes you need the ability to be specific. English is a complicated language, but limiting how many adjectives can apply to a particular noun would make it much worse in my opinion.
As for the original question, a pure virtual function is a function that must be implemented in a derived class, while a private function is a function that can’t be accessed outside of the class, not even from derived classes. A destructor is a function used to clean up when an object goes out of scope; I don’t think anything about the destructor is important in this case, it just happens to be a convenient member function to use.
The combination would make it impossible to instantiate objects of the class (because of the pure virtual function) or objects of classes that inherit from it (because the pure virtual function can’t be accessed, let alone implemented, from a derived class). That rules out much of what you’d want to do with a class. You’re left with static data and functions, and nested types. Overall, the best I can tell, you would use that to make the class imitate a namespace. But for the last twenty years, you don’t have to imitate namespaces: C++ has them.
You might still find somebody trying to avoid using actual namespaces because of a vague fear of argument dependent lookup, but to be honest, I’ve never seen argument dependent lookup call the wrong function. Some programmers oppose it in principle, but in practice it doesn’t seem to cause much trouble.
(Though, C does have its share of mental burdens. Understanding automatic type conversion is quite a beast.)
OTOH preprocessor directives grow the base C a bit. It's still very tiny, though.
Like all abstractions there are corner cases that force you to deal with the underlying complexity.
Sure, C++ is double of that, but it's still long. In comparison, Java language specs is around 800 pages, Ruby 330 pages, and C# 500 pages.
Subtle UB, as much of a headache as it can be to a programmer using the language, in this case leads to simpler implementation of a compiler.
simplicity for the user and simplicity for the compiler writer are totally different things. Java is simpler for the user but more complex for the implementer, and C is more complex for the user but simpler for the implementer.
The rules for TBAA are complex, and many C/C++ programs violate those rules because it's so hard to actually make sure you're not violating them, and half of the purpose of using C/C++ is actually to be able to do the kind of type-punning that TBAA prohibits.
C's memory model is trivial by comparison.
To be fair, that now includes a substantial standard library. The language + preprocessor spec ends on page 197 and starts on page 19, for a total of 178 pages.
(Why the lack of formal semantics? My guess is that all of these languages, to varying degree, are too complex to easily formalize...)
What about Haskell?
This only applies if you're writing 100% of the code. Not having coworkers to mess around with every corner-case of the langage is a rare privilege.
The same could be said about Lisp. Would you trade your C compiler for Lisp one?