Compile time vs Runtime

Compile-time and runtime refer to different stages in the lifecycle of a program. Understanding the difference between them helps in identifying and fixing errors effectively

Compile-time

Definition: Compile-time refers to the period when the source code is translated into executable code by the compiler. Errors detected during this phase prevent the code from being compiled into an executable file.

Errors Detected at Compile-time:

1. Syntax Errors: Occur when the code does not follow the grammatical rules of the language.

2. Semantic Errors: Occur when the code is syntactically correct but semantically incorrect or illogical.

Examples:

Syntax Error:

int a, b: // Incorrect syntax; should end with a semicolon

Error Message:

error: expected ‘;’ before ‘:’ token

Semantic Error:

int a = 5;
int b;
a + b = 10; // Invalid assignment; cannot assign a value to an expression

Error Message:

error: lvalue required as left operand of assignment

Compile-time Process:

• The compiler checks the code for syntax and semantic correctness.

• If no errors are found, it generates an executable file. If errors are found, the compiler reports them, and the program must be corrected before successful compilation.

Runtime

Definition: Runtime refers to the period when the compiled executable code is executed. Runtime errors occur while the program is running, after successful compilation.

Errors Detected at Runtime:

1. Division by Zero: Attempting to divide a number by zero.

2. Null Pointer Dereference: Accessing memory through a null pointer.

3. Array Out of Bounds: Accessing elements outside the bounds of an array.

4. Memory Leaks: Failing to deallocate memory that is no longer needed.

Example:

Division by Zero:

int a = 10;
int b = 0;
int result = a / b; // Runtime error: division by zero

Possible Runtime Error:

Floating point exception (core dumped)

Null Pointer Dereference:

int *ptr = NULL;
int value = *ptr; // Runtime error: dereferencing a null pointer

Possible Runtime Error:

Segmentation fault (core dumped)

Array Out of Bounds:

int arr[5];
arr[10] = 100; // Runtime error: accessing out-of-bounds index

Possible Runtime Error:

Segmentation fault (core dumped)

Runtime Process:

• The program is executed by the operating system.

• Errors that occur during execution (runtime errors) may cause the program to crash or behave unpredictably.

• These errors are often harder to detect and debug because they depend on the specific inputs and conditions present during execution.