3

I'm new to C++. I heard that dividing by 0 leads to a run time error, but when I tried it, it threw me a compiler error C2124 and didn't create an object file, so does the compiler automatically run the code to see whether it's executable before creating an object file? (I'm using Visual studio community btw)

int main() { int a = 9 / 0; } 
6
  • Are you dividing by the constant 0 or are you using variables to produce the division by zero? Commented Aug 28, 2020 at 15:31
  • 3
    It's Undefined Behaviour, therefore both answers are correct, as well as "it will run without error" and "you will get nasal demons" Commented Aug 28, 2020 at 15:32
  • @Steve here is the code int main() { int a = 9 / 0; } Commented Aug 28, 2020 at 15:33
  • 1
    The compiler doesn't have to run your code to point its finger. It is the parser that tells you that this code contains a division by zero. Try with int div = 0; int a = 9 / div; Commented Aug 28, 2020 at 15:35
  • if you write int x= 5/3; then typically the division is not made at runtime Commented Aug 28, 2020 at 15:38

1 Answer 1

4

This depends on the context in which you do a division by 0. If you do it in a context that only needs the expression to be evaluated at run-time, then it's undefined behavior:

void f() { int a = 9 / 0; // UB } 

Note that UB means anything can happen, including the compiler noticing that the code is buggy, and refusing to compile it. In practice, when you divide a constant by 0, the compiler is likely to issue at least a warning.

If it happens in a constexpr or consteval context, then the behavior is well-defined, and the compiler is required to not compile the code:

constexpr void f() { int a = 9 / 0; // error, never produces a valid result } 

or

void f() { constexpr int a = 9 / 0; // error } 

The primary reason for this is that all behavior is well defined at compile time, and so there is no UB in these contexts.

Sign up to request clarification or add additional context in comments.

4 Comments

can you give a reference? I didnt find it. Isnt it strange that dividing by the literal 0 is UB while in constrant expressions it can be well-defined?
@idclev463035818 Well-defined, not well-formed, in fact it's ill-formed. Is that your question? Added a line at the end to explain.
yes thats what I meant. Forgot that there is no UB at compile time, but still I wonder why what is the benefit of not guaranteeing an error for int a = 9 / 0;
@idclev463035818 Not entirely sure. Probably requires extra wording to make this (very) particular case ill-formed, and it's not worth it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.