3 ms·
But C doesn't let programs fail. (or at least not loudly) That's the problem, to me at least. I've had this code yesterday on an embedded arm cortex m0: bool
by AnyTimeTraveler 5y ago
But C doesn't let programs fail. (or at least not loudly)
That's the problem, to me at least.
I've had this code yesterday on an embedded arm cortex m0:
bool tx_byte(char msg) {
for (int i = 0; i < 8; i++) {
tx_bit((msg >> i) & 1);
}
}
This function wouldn't return.
What's even stranger, the variable i would increment past 7. The for-loop just continues.
I got a warning about the missing return statement in that function, but didn't think there could be a connection to my bug.
It turned out that adding that return after the for loop fixed it.
The warning was one among about 100 others, as I was refactoring quite some code at the time.
I only started working on the warnings after I had decided that me an two of my colleagues were just overlooking something and would fix the bug another day.
All that I wanted to say is that, no, C doesn't make you aware of what is happening. It has this giant pit of UB that does weird things when you fall into it.
I was lucky that in my instance, I got a warning. I know other UB just works most of the time and goes unwarned.
- ascar 5y agoSounds like the compiler didn't correctly adhere to calling conventions without an explicit return statement. Wouldn't that even be a compiler bug allowing no return statements, but then incorrectly handling scope?
- tux3 5y agoIt's undefined behavior, the compiler can do whatever it wants. Here the compiler assumes the function never returns (because it would be UB since there's no return statement), so it looks like it just didn't bother to add a loop exit at all. This is standard compliant.
- nybble41 5y agoActually it's only undefined (per C99 anyway) if the return value is used: > If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined. So if the return value is never used then there is no undefined behavior and a standards-compliant compiler isn't allowed to optimize away the loop exit condition.
- nsajko 5y ago> I got a warning about the missing return statement in that function, but didn't think there could be a connection to my bug. This is the whole story, really.
- leovailati 5y agoTo complement your example, there are also cases when everything coincidentally happens to work fine. For example: https://stackoverflow.com/questions/7280877/why-and-how-does-gcc-compile-a-function-with-a-missing-return-statement https://stackoverflow.com/questions/7280877/why-and-how-does...