编译时错误

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

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

下面是一个演示编译时错误的示例:
C++语言示例:

// C++ program to illustrate
// syntax error
#include <iostream>
using namespace std;

int main()
{
    int x = 10;
    int y = 15;

// semicolon missed
    cout << " "<< (x, y);
}

// this code is contributed by shivanisinghss2110

C语言示例:

// C program to illustrate
// syntax error

#include<stdio.h>

void main()
{
    int x = 10;
    int y = 15;

// semicolon missed
    printf("%d", (x, y));
}

运行错误:

error: expected ';' before '}' token

运行时错误

成功编译后在程序执行(运行时)过程中发生的错误称为运行时错误。 最常见的运行时错误之一是除以零,也称为除法错误。 这些类型的错误很难找到,因为编译器没有指向错误发生的行。
要获得更多理解,请运行下面给出的示例 -
C++示例代码

// C++ program to illustrate
// run-time error

#include <iostream>
using namespace std;

int main()
{
    int n = 9, div = 0;

    // wrong logic
    // number is divided by 0,
    // so this program abnormally terminates
    div = n/0;

    cout <<"result = " << div;
}

// This code is contributed by shivanisinghss2110

C语言示例代码

// C program to illustrate
// run-time error

#include<stdio.h>

void main()
{
    int n = 9, div = 0;

    // wrong logic
    // number is divided by 0,
    // so this program abnormally terminates
    div = n/0;

    printf("result = %d", div);
}

运行结果:

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

在给定的示例中,存在除以零错误。 这是运行时错误的示例,即运行程序时发生的错误。
编译时和运行时错误的区别是:

编译时错误 运行时错误
编译时错误是编译器检测到的语法错误。 运行时错误是编译器未检测到并产生错误结果的错误。
编译时错误会阻止代码运行,因为它检测到一些语法错误。 运行时错误阻止代码完全执行。
包括语法错误,例如缺少分号(;),关键字和标识符拼写错误等。 包括错误,例如将数字除以零,找到负数的平方根等。