Tuấn Đoàn
Tuấn Đoàn

Reputation: 103

Dividing by 0 is a compiler error or a runtime error

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; }

Upvotes: 3

Views: 1267

Answers (1)

cigien
cigien

Reputation: 60208

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.

Upvotes: 4

Related Questions