A compiler in C language translates human-readable source code into machine-readable object code that can be executed by a computer. Here's a simple explanation along with an example:
Lexical Analysis: The compiler breaks down the source code into tokens like keywords, identifiers, constants, and symbols.
Syntax Analysis (Parsing): It checks if the arrangement of tokens follows the rules of the programming language's grammar.
Semantic Analysis: It ensures that the program follows the language's rules and checks for logical errors.
Intermediate Code Generation: The compiler generates an intermediate representation of the source code.
Optimization: The intermediate code is optimized to improve the efficiency of the resulting machine code.
Code Generation: Finally, the compiler produces the machine code suitable for the target platform.
Here's a simplified example of a compiler in C that converts a basic arithmetic expression into machine code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// Function to evaluate arithmetic expression
int evaluate(char *expr) {
char *ptr = expr;
int result = 0;
int num = 0;
char op = '+';
while (*ptr) {
if (isdigit(*ptr)) {
num = num * 10 + (*ptr - '0');
} else if (*ptr == '+' || *ptr == '-') {
if (op == '+') {
result += num;
} else if (op == '-') {
result -= num;
}
num = 0;
op = *ptr;
}
ptr++;
}
if (op == '+') {
result += num;
} else if (op == '-') {
result -= num;
}
return result;
}
int main() {
char expr[100];
printf("Enter an arithmetic expression: ");
scanf("%s", expr);
int result = evaluate(expr);
printf("Result: %d\n", result);
return 0;
}
In this example
evaluate
function parses the arithmetic expression and calculates the result.main
function prompts the user to input an arithmetic expression, passes it to the evaluate
function, and prints the result.This example is a highly simplified version of a compiler. In a real compiler, each step would be much more complex and involve multiple stages of analysis and optimization.