Type Checking
Type Checking
DESCRIPTION
• Type checking ensures that operations are performed on compatible data types,
preventing type errors.
• It is a part of semantic analysis in the compilation process.
• Helps detect type mismatches in expressions and assignments before execution.
• Improves code reliability by catching errors at compile-time or runtime.
• Prevents unintended operations between incompatible data types, ensuring type
safety.
• Reduces the chances of undefined behaviour and runtime crashes.
• Can be classified into Static Type Checking (done at compile-time) and
Dynamic Type Checking (done at runtime).
• Static Type Checking is used in languages like C, Java, and C++, where type
errors are caught during compilation.
• Dynamic Type Checking is used in languages like Python and JavaScript,
where types are checked at runtime.
• Compiler lexical analysis recognizes tokens but does not perform type
checking.
• Syntax analysis ensures correct syntax but does not validate data types.
• Semantic analysis performs type checking to ensure correct operations on
variables.
• Helps in intermediate code generation by determining appropriate temporary
variables.
• Used in code optimization to enhance program performance by ensuring type
consistency.
• During target code generation, type checking ensures correct instruction
generation for execution.
• Prevents common programming errors such as assigning a float value to an
integer variable without explicit conversion.
• Example of type mismatch error:
int x = 10;
float y = 5.5;
x = x + y;
• Ensures that operations like arithmetic, relational, and logical operations follow
correct type rules.
• Type checking is crucial for memory management, avoiding issues like
accessing incompatible memory locations.
PROGRAM :
#include <stdio.h>
#include <string.h>
#include <ctype.h>
typedef struct {
char name[20];
char type[10];
} Symbol;
Symbol symbolTable[MAX_SYMBOLS];
int symbolCount = 0;
if (typeRes == NULL) {
printf("\n\tError: Undefined variable '%s'.\n", res);
return;
}
if (type1 == NULL) {
printf("\n\tError: Undefined variable '%s'.\n", op1);
return;
}
if (type2 == NULL) {
printf("\n\tError: Undefined variable '%s'.\n", op2);
return;
}
if (strcmp(type1, type2) != 0) {
printf("\n\tError: Type mismatch in expression '%s = %s %c %s'.\n", res, op1, operator,
op2);
return;
}
int main() {
char varName[20], type[10];
char res[20], op1[20], op2[20], operator;
int n;
printf("\nEnter expression in the form 'res = var1 operator var2' (e.g., a = b + c):\n");
scanf("%s = %s %c %s", res, op1, &operator, op2);