I thought there was a level of optimisation at compilation that would actually spot that when figuring out zero is only used there and immediately and always 0 or something, did I dream this or is it real ? Still a beginner
Pretty sure this is actually UB (the compuler can choose to execute the Zero function before getting the value for i for the addition and therefore make x=-1).
I'm pretty sure, last time my compiler called me out on this, that they caught in-line arithmetic. But multi-step operations with uncertain results that could result in division by zero are still chill, so we should be able to design a surefire operation that still looks uncertain to the compiler.
(which means that the value might be changed by something else so the compiler can't assume it'll remain 0 by the time execution reaches the next line)
It is real at least in Java. Primitives and String should do inlining of compile-time constants. If zero is never modified, it is "effectively final" and the variable zero should be replaced by a literal.
x would then be a compile-time expression and replaced by... well, it would throw I guess?
[EDIT] Oh. Apparently they MUST be declared final explicitely, to avoid some edgecases about manipulating the variable in sneaky ways.
just put it behind a function in a static initializer and even though it's all final contants, javac will fail to optimize any of it. It's a shockingly basic compiler still.
To be fair, java does runtime optimization, which can result in better optimization overall. It doesn't always (and short lived programs can't really take advantage of runtime optimization), but iirc in some cases, Java can outperform C++.
Any C compiler will compile both of those (if you enable optimisations) as a single UD2 instruction (https://www.felixcloutier.com/x86/ud). It will not even bother with assigning the 1 anywhere or doing a division.
So, I actually tried it and I was not correct. With -O2, gcc will compile it as UD2, however clang will just ignore the division and the code will happily continue running. Division by zero is UB (undefined behavior) in the standard, so the compiler can basically do whatever it wants.
Everyone else has answered the question but I thought I'd point you to this series I've been enjoying at the moment, it's about how compilers work and all the steps involved, building up the intuition layer by layer and piece by piece, you might find it useful!
Most compiler probably could spot it, but the rules of the languages don't assume that level of sophistication and require them to compile it because it'd be annoying for some programs to compile under some compilers, but not under others. C compilers in particular can be really funny with things like this, they spot a mistake in your code and just optimize whole damn function away because "hey, it didn't work right anyway"
I once had a great case in GCC where it would detect the roundabout divide by zero and emit a UD0 instruction instead of compiling the rest of the function. For context it was something like an off-by-one error in a decrementing for loop (should've stopped at 1 but accidentally went to 0), and GCC optimised out the entire loop and replaced it with an immediate UD0.
Most compilers are mathematically proving the intended outcome if this is the static analysis (unless the outcome is known as undefined). That's why interpreted or JIT code is usually more buggy on run, because the share of code that can undergo the static analysis is lower, but it's still checked statically whenever it's possible.
Yeahhhh but I like to understand the jokes I'm looking at and their context. Also, just given the absurd amount of positive and detailed explanatory replies, I can safely assume it was a good thing to ask :)
In c++ there is a thing called compile time computation... It turns a algorithm string of literals into a single literal. It happens in other languages as well but this is a problem of specific more often then a problem with the compiler. The first example is defined as not being legal in most(all? Not sure) languages where as the second is a run time error. By pushing computation to compile time we make run time errors into to compile failures optimize has little to do with it. But yes theoptimzer can trace that shit and has been able to for years and years it just was not specificed what happened (ub ex: c, c++) or it was a running error(ex: java, python, c#) and now with compile time computation (ex: kotlin and c++ in some cases, as long as zero is not user define at point). Turns out you can and often do lie to your compiler all the time and it assumes you don't and so bad/strange things happen. This is not a bug and is sometimes a feature but more importantatly it is feasible unlike proving the lack of undefined behavior in all cases.
More complex path conditions may not be caught though. Or introducing some fake nondeterminism
By the way, C++ will happily compile this and depending on the compiler implementation will compile to a NOP. The freedom of doing whatever you like when you detect UB
Division by zero isn't necessarily an error. Several CPU architectures do support division by zero at hardware-level and don't treat it as an error, even though the result isn't mathematically correct. Other might throw an exception when encountering a "divide" instruction with zero as a divisor.
That's why in the C programming language, division by zero isn't an error, but its result is undefined or platform-specific according to the standard.
In a similar way, dereferencing a null pointer isn’t always an error either. As long as 0 is a valid address, you can have all sorts of fun with this. On a microcontroller you often don’t get a null pointer hardware interrupt, but instead your application starts acting unpredictably because it’s started executed random instructions from 0.
Even funnier if you happen to allocate some data / struct at 0 and then try to hand it to a lib function not expecting 0 to be a valid address. And as adding debugging tools influences allocation, this can be quite the pain xD
Yeah, the compiler is there to protect you from the bouncer inside.
One of the things I say in my intro CS classes (taught in Java) is that people think compiler errors are worse than runtime errors, which are worse than logic errors, because "at least it runs". But really it's the other way around. A program with a logic error is further from being correct, because logic errors are generally harder to debug and fix.
We've recently integrated typescript at work, and one of the things we're learning is that typescript is happy to let you choose between something being a runtime error and a compile time error. My rule of thumb is now that if you're using 'any', don't, and if you see it used, take the time to purge it like the blight it is.
I see a lot of people who are like "okay, I've written the code, now I just need to get rid of the compiler errors". Obviously nonsense to you and me, not always obvious to all the sudents.
I'm pretty sure that's up to the IDE in a lot of languages. I've had students turn in Java code with unicode variable names that compiled and ran just fine. (I told them to turn the variable names into words and try again, because I wasn't going to read their code.)
Check if the stack is in writable memory. On x86 realmode if the stack segment is in a non existant space the memory is read out as 0xff and can not be written (not even a pagefault)
The issue isn't IDE vs nano. It's static analyzer vs no static analyzer. It only looks like it's IDE vs nano because IDEs typically run a linter (i.e. lightweight static analyzer) by default and nano doesn't.
You should be running static analysis on your code regardless of what editor you're using. And probably with more thorough static analyzers than the ones that are enabled by default in most IDEs. The bugs that can be caught in static analysis aren't all as obvious as this one.
Again, this is all external tooling. OP was talking compilers. Also these are all things that also get implemented in your cicd pipeline. This shit would get caught by ten different tools where I work.
Honestly I meant to reply to OP and clicked the wrong reply button.
I suspect OP is seeing the IDE surface linter errors in the same place that it surfaces compiler errors and so is assuming that the errors come from the same place. Hence "compiler" errors in the IDE that they don't get with nano which are actually caused by just running a linter.
It's either that or the IDE is using different compiler flags (or even a different compiler version) than OP is using when running the compiler outside of the IDE (in which case they'd actually be right about them being compiler errors and I'd be wrong about it being due to a separate static analyzer).
Absolutely agree with you that this stuff should be implemented in the CI/CD pipeline (and it is where I work too). My point wasn't about where or when static analyzers should be run but simply that they should be run.
Really? Right in front of my "You do know that's worse?" meme?
... Aaaaand I have no idea how to post a meme in comments so here's what I made with a generator :( https://imgflip.com/i/b1tjok
[EDIT] I'll admit I spent waaaaay too much time figuring out how to use a meme generator to not at least show it. No option in the mobile web view, so I had to go on a computer to learn we can include gifs here but images seem disabled on this sub.
I, for one, love having to rely on the quality of my testing habits only to have QA and a code lead pinging me 5 hours later about how the thing is broken.
Somehow the shame is even worse when someone on my team fixes it and puts me on the review.
I’m so confused by all these comments about IDEs, floats, and runtime errors.
Any half decent compiler will convert zero to a literal and just inline the statement. This should cause a compilation error. Editors aren’t always configured to use the compiler as a backend for syntax checking, they could be using treesitter or a dumb LSP.
For example, C can be a real pain to setup autocomplete because the editor needs so much build context to work effectively. It’s common to use no autocomplete or something naive instead.
I am not entirely sure of the reason behind this, but I noticed a similar behavior with Type casting and conversion when working in Java. If my understanding is correct, the former is detected at compile time because 1/0 is a literal calculated at compile time and hence the issue is caught promptly. The latter one however uses 1/zero. Now the result should be same, but the compiler allows this code to compile because the actual execution where zero = 0 is translated happens at runtime. Correct me if I am wrong.
it treats them differently not because of the type, but probably because the IDE is simple and only recognizes the error if it's an explicit / 0 written out.
it treats the expression 1 / zero the same way it treats 1 / five; it views them without any extra context about their actual values.
Put in a function which may be called only on a Leap year in March or July on the 3rd day of the month only if the 5th is a Sunday (so 3rd is Friday) anytime after 3 PM and you have the perfectly placed disaster for the outsourced contractor they replaced you with.
int x = 10;
if (x==) {}}
function()
x++1;
y is undefined;
fuck you compiler++;
/ half a comment
x = x <>+%%+<> 100
struct struct {
struct struct;
struct struct;
}
std = void;
true = false;
#define if(x) if(!(x))
x = 1/0 // Compiler, how do you feel having a SegmentationFault on your brain!?
Similarly with return; and code after it. Just do if (true) return; and it's fine. Quite handy when you need to stop the method earlier without need to put breakpoints there etc.
like i know that you can't take 0 steps to reach 1 but its a very useful thing in python that probably be a real good thing but not in c or any others since it's just more work in the compiler
Always tought the same. Wouldn't it fix a ton of issues without much side effects? Like I understand it would be technically not accurate but... should we care? :D
Yes, we should care. Having a critical bug in a software is unfun, but having an invisible/suppressed error running for a while is a nightmare. What if you have silent 0-divisions in your billing software, and you discover the scale of the issue at the end of the quarter when you realize you're missing half of your budget ?
why tf is division by zero a syntax error at all. it is syntactically correct to devide a number by a number. just let me write my code as I see fit and let me die my division-by-zero-runtime-error death in peace.
737
u/AaronTheElite007 Sep 23 '26
Compiler: “This is runtime’s problem. Dude owes me money”
1.7k
u/OxymoreReddit Sep 23 '26
I thought there was a level of optimisation at compilation that would actually spot that when figuring out
zerois only used there and immediately and always 0 or something, did I dream this or is it real ? Still a beginner997
u/lokiOdUa Sep 23 '26
What's the point moving error from compilation to runtime?
56
u/Flaky-Low-2262 Sep 23 '26
This Pre-Compiler stuff not the Compiler.
Thats different
10
u/cheezballs Sep 23 '26
I feel like it'd get caught right?
135
u/caleblbaker Sep 23 '26 edited Sep 23 '26
Insert meme of Chidi saying "Okay but that's worse. You do see how that's worse, right?" (I'm too lazy to find the actual meme)
14
u/sitilge Sep 23 '26
IDE
ide
12
u/suavebriisa Sep 23 '26
Compiler passed the buck straight to runtime
7
u/Zirkulaerkubus Sep 23 '26
constexpr it
60
u/Most_Researcher_3010 Sep 23 '26
Compiler really said: “Nice try, I’ll wait until runtime.” 💀
5
u/alt_for_1 Sep 23 '26
A modern compiler would catch this. The IDE’s static code analysis and most linters will not.
5
u/Nolear Sep 23 '26
Red for variable names is crazy choice
5
u/program_the_world Sep 23 '26
I’m so confused by all these comments about IDEs, floats, and runtime errors.
Any half decent compiler will convert zero to a literal and just inline the statement. This should cause a compilation error. Editors aren’t always configured to use the compiler as a backend for syntax checking, they could be using treesitter or a dumb LSP.
For example, C can be a real pain to setup autocomplete because the editor needs so much build context to work effectively. It’s common to use no autocomplete or something naive instead.
3
u/namalleh Sep 23 '26
dude, const propagation
3
u/National-Explorer755 Sep 23 '26
I am not entirely sure of the reason behind this, but I noticed a similar behavior with Type casting and conversion when working in Java. If my understanding is correct, the former is detected at compile time because 1/0 is a literal calculated at compile time and hence the issue is caught promptly. The latter one however uses 1/zero. Now the result should be same, but the compiler allows this code to compile because the actual execution where zero = 0 is translated happens at runtime. Correct me if I am wrong.
3
u/JackNotOLantern Sep 23 '26
Java:
"NOOOO, UNREACHABLE CODE"
"Everything seems to be on order"
4
u/Quick_Isopod_5781 Sep 23 '26
FINALLY some syntax humor
2
u/utl94_nordviking Sep 23 '26
Not my compiler.
2
u/Apprehensive_Bit7392 Sep 23 '26
Make it const int zero = 0; and the squiggle comes back.
2
u/LupusCanis42 Sep 23 '26
Why the hell would you even detect that?
If you specifically write down a division by zero with magic numbers you deserve to land in the hard fault handler
2
u/Just_Scar4703 Sep 24 '26
constexpr
2
u/Elkatra2 Sep 23 '26
cc file.c -o runtime_bomb
1
u/mookanana Sep 23 '26
the first treats 0 as a float value, the second is defined as int? would compiler treat these datatypes differently?
1
u/SnugglyCoderGuy Sep 23 '26
1
u/kishaloy Sep 23 '26
Put in a function which may be called only on a Leap year in March or July on the 3rd day of the month only if the 5th is a Sunday (so 3rd is Friday) anytime after 3 PM and you have the perfectly placed disaster for the outsourced contractor they replaced you with.
Happy coding.
1
u/an_agreeing_dothraki Sep 23 '26
watching a junior discover runtime errors
1
u/saxxonpike Sep 23 '26
To be fair, some compilers will inline these and crater anyway.
1
u/sammystevens Sep 23 '26
bros never heard of 1e-19 before
1
u/Busy-Complaint-7 Sep 23 '26
Exception right ! Runtime it will terminate program abnormally
1
u/Ok-Scheme-913 Sep 23 '26
I see the semester has just started.
1
u/AllCowsAreBurgers Sep 23 '26
unter das os
1
u/KiwiObserver Sep 24 '26
My method is to use a variable passed by the invoker, which I known contains a constrained set of values, but the compiler has no information about.
1
u/tbhaxor Sep 24 '26
No complaints now
1
u/Glum_Preference_2936 Sep 24 '26
Real programmer declare it in a different translation unit.
1
u/False-Beautiful-1246 Sep 24 '26
"No one will notice if there is a bigger problem"
1
u/crmsncbr Sep 24 '26
This doesn't work on most compilers anymore... You need to add an extra step or two to create zero without assigning zero.
1
u/warwilf Sep 24 '26
Well the value is variable so, valid
1
u/haish10 Sep 25 '26
That becuase it must put the result on the static part when you do it the other way it dynmic the cpu done that
1
u/facebrocolis Sep 26 '26
Yeah, infinity is obviously a float
1
u/Adaptor2000 Sep 27 '26
I would be such a hack0r if it wasn't for the compiler who keeps on sabotaging my efforts...
1
u/Fun_Moose_5307 Sep 27 '26
Guys…
int(“0”)
1
u/alantao03 Sep 28 '26
Constant value propagation!
1
u/Dee4WasTaken Sep 29 '26
Great going you made a logic black hole now we're all doomed to a logical demise.
1
u/ilnarildarovuch Sep 30 '26
volatile asm
1
u/Right_Ear_2230 Oct 17 '26
C compiler either way:
1
u/notexecutive Sep 23 '26
Compile error vs Runtime Error :)
1
u/eleg-phant Sep 23 '26
Isn't this an interpreter and not a compiler?
0
u/GreatScottGatsby Sep 23 '26
What is the quickest way to trigger a hardware fault for 500 alex?
-1
u/vlken69 Sep 23 '26
Similarly with
return;and code after it. Just doif (true) return;and it's fine. Quite handy when you need to stop the method earlier without need to put breakpoints there etc.-2
u/jevin_dev Sep 23 '26
i must ask way don't they just return 0
4
u/Quaschimodo Sep 23 '26
why tf is division by zero a syntax error at all. it is syntactically correct to devide a number by a number. just let me write my code as I see fit and let me die my division-by-zero-runtime-error death in peace.