📜  编译时错误和运行时错误之间的区别

📅  最后修改于: 2021-09-14 02:04:36             🧑  作者: Mango

编译时错误:当您违反编写语法规则时发生的错误称为编译时错误。此编译器错误表示在编译代码之前必须修复某些内容。所有这些错误都被编译器检测到,因此被称为编译时错误。
最常见的编译时错误是:

  • 缺少括号 ( } )
  • 打印变量的值而不声明它
  • 缺少分号(终止符)

下面是一个演示编译时错误的示例:

// C program to illustrate
// syntax error
  
#include
  
void main()
{
    int x = 10;
    int y = 15; 
      
// semicolon missed
    printf("%d", (x, y)) 
}

错误:

error: expected ';' before '}' token

运行时错误:成功编译后在程序执行期间(运行时)发生的错误称为运行时错误。最常见的运行时错误之一是被零除,也称为除法错误。这些类型的错误很难找到,因为编译器没有指向发生错误的行。

为了更多理解,请运行下面给出的示例。

// C program to illustrate
// run-time error
  
#include
  
void main()
{
    int n = 9, div = 0;
    
    // wrong logic
    // number is divided by 0,
    // so this program abnormally terminates
    div = n/0;
      
    printf("resut = %d", div);
}

错误:

warning: division by zero [-Wdiv-by-zero]
     div = n/0;

在给定的示例中,除以零错误。这是运行时错误的示例,即在运行程序时发生的错误。

编译时错误和运行时错误之间的区别是:

Compile-Time Errors Runtime-Errors
These are the syntax errors which are detected by the compiler. These are the errors which are not detected by the compiler and produce wrong results.
They prevent the code from running as it detects some syntax errors. They prevent the code from complete execution.
It includes syntax errors such as missing of semicolon(;), misspelling of keywords and identifiers etc. It includes errors such as dividing a number by zero, finding square root of a negative number etc.