CD Lab
CD Lab
(Regulations 2021)
SEMESTER V
(ACADEMIC YEAR 2024-25)
REGISTER NUMBER
1
SSM COLLEGE OF ENGINEERING
KOMARAPALAYAM- 638183.
2
Internal Examiner ExternalExaminer
INDEX
SI NAME OF PAGE
NO DATE THEEXPERIMENT NO MARK SIGN
20-09-2024 16
3 Lexical analyzer using lex tool
14-10-2024 28
6 Calculator using lex and yacc
25-11-2024 51
11 Implement the back end of the
compiler
25-11-2024 55
12 Simple code optimization
3
Ex No:1
Date: Symbol table
AIM:
To write a C program to implement a symbol table.
INTRODUCTION:
ALGORITHM:
4
SYMBOL TABLE:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<string.h>
#include<math.h>
#include<ctype.h>
voidmain() {
int i = 0 , j = 0 , x = 0 ,n, flag=0;
void*p, *add [15];
char ch,srch,b[15],d[15],c;
//clrscr();
printf ("expression terminated by $:");
while(( c = 1 getchar())!='$')
{
5
b[i]=c; i++;
}
n = i – 1;
printf ("givenexpression:");
i = 0;
while(i<=n)
{
printf("%c",b[i]);
i++;
}
printf("symbol table\n");
printf("symbol\taddr\ttype\n");
while (j<=n)
{
c=b[j];
if (isalpha (toascii(c)))
{
if (j==n)
{
p=malloc(c);
add [x]=p; d[x]=c;
printf("%c\t%d\tidentifier\n",c,p);
} else
{
ch=b[j+1];
if (ch=='+'|| ch=='-'|| ch=='*' || ch=='=')
x++; } }
{ p=malloc(c);
add [x]=p;
d [x]=c;
printf("%c\t%d\tidentifier\n",c,p);
}
j++;
}
printf("the symbol is to be searched\n");
srch=getch(); for(i=0;i<=x;i++)
{
if (srch==d(i)) { printf("symbol printf ("%c%s%d\n",srch, "@address", add[i]) ; flag=1; found\n");
}}
if (flag==0) printf("symbol not found\n");
//getch();
6
OUTPUT:
RESULT:
Thus the C program to implement the symbol table was executed and the output is verified.
7
Ex No:2
Date: DEVELOP A LEXICAL ANALYZER TO
RECOGNIZE A FEW PATTERNS IN C
AIM:
INTRODUCTION:
TOKEN:
A token is a structure representing a lexeme that explicitly indicates its categorization for the Purpose
of parsing. A category of token is what in linguistics might be called a par-tof- speech. Examples of
token categories may include “identifier” and “integer literal”, althoughthe set of Token differ in
different programming languages.
The process of forming tokens from an input stream of characters is called tokenization.
ALGORITHM:
10
if(strcmp(ch,a)==0)
{
fscanf(fop,"%s",ch);
printf("\t\t%s\t:\t%s\n",a,ch);
flag=1;
}
fscanf(fop,"%s",ch);
}
rewind(fop);
fscanf(fk,"%s",ch);
while(!feof(fk))
{
if(strcmp(ch,a)==0)
{
fscanf(fk,"%k",ch);
printf("\t\t%s\t:\tKeyword\n",a);
flag=1; }
fscanf(fk,"%s",ch);
}
rewind(fk);
if(flag==0)
{
if(isdigit(a[0]))
printf("\t\t%s\t:\tConstant\n",a);
else
printf("\t\t%s\t:\tIdentifier\n",a);
}
flag=0;
fscanf(fi,"%s",a);
}
getch();
}
Key.C:
int
11
void
main
char
if for
while
else
printf
scanf
FILE
Includ
e
stdio.
h
conio.
h
iostre
am.h
Oper.C
:
( open para
) closepara
{ openbrace
} closebrace
< lesser
> greater
" doublequote ' singlequote
: colon
; semicolon
# preprocessor
= equal
== asign
% percentage
^ bitwise
& reference
12
* star
+ add
- sub
\ backslash
/ slash
Input.C:
#include
"stdio.h"
#include
"conio.h" void
main() { int
a=10,b,c; a=b*c;
getch();
}
OUTPUT:
13
14
RESULT:
Thus the above program for developing the lexical the lexical analyzer and recognizing
the few pattern s in C is executed successfully and the output is verified.
Ex no:3
IMPLEMENTATION OF LEXICAL ANALYZER USING LEX TOOL
15
Date:
AIM:
THEORY:
ALGORITHM:
16
1. Start the program
2. Lex program consists of three parts.
3. Declaration %% 4. Translation rules %%
5. Auxiliary procedure.
6. The declaration section includes declaration of variables, main test, constants and
regular
7. Definitions.
8. Translation rule of lex program are statements of the form
9. P1{action}
10. P2{action}
11. …..
12. …..
13. Pn{action}
14. Write program in the vi editor and save it with .1 extension.
15. Compile the lex program with lex compiler to produce output file as lex.yy.c.
16. Eg. $ lex filename.1
17. $gcc lex.yy.c-11
18. Compile that file with C compiler and verify the output.
LEX SOURCE:
18
if(isdigit(c))
state=2;
if(isrelop(c))
state=3; if(c==';')
printf("\t<3,3>\n");
if(c=='=')
printf("\t<4,4>\n");
break;
case 1:
if(!isalnum(c)) {
token[tlen]='\o';
printf("\b\t<1,%p>\n",getAddress(token));
state=0;
pos--;
}
else
token[tlen++]=c;
break;
case 2:
if(!isdigit(c))
{
printf("\b\t<2,%p>\n",&input[pos]);
state=0;
pos--;
}
break;
case 3:
id=input[pos-1];
if(c=='=')
printf("\t<%d,%d>\n",id*10,id*10);
else
{
printf("\b\t<%d,%d>\n",id,id);
pos--;
}
state=0;
break;
}
pos++;
}
while(c!=0);
getch();
return 0;
}
OUTPUT
19
RESULT:
Thus the program for the exercise on lexical analysis using lex has been successfully
executed and output is verified.
20
Ex No:4
ENERATE YACC SPECIFICATION FOR A FEW SYNTACTIC
Date:
CATEGORIES.
AIM :
To write a c program to do exercise on syntax analysis using YACC.
INTRODUCTION :
YACC (yet another compiler) is a program designed to produce designed to
compile a LALR (1) grammar and to produce the source code of the synthetically
analyses of the language produced by the grammar.
ALGORITHM :
1. Start the program.
2. Write the code for parser. l in the declaration port.
3. Write the code for the ‘y’ parser.
4. Also write the code for different arithmetical operations.
5. Write additional code to print the result of computation.
6. Execute and verify it.
7. Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
char s[5];
21
clrscr();
printf("\n Enter any operator:");
gets(s);
switch(s[0])
{
case'>':
if(s[1]=='=')
printf("\n Greater than or equal");
else
printf("\n Greater than");
break;
case'<':
if(s[1]=='=')
printf("\n Less than or equal");
else
printf("\nLess than");
break;
case'=':
if(s[1]=='=')
printf("\nEqual to");
else
printf("\nAssignment");
break;
case'!':
if(s[1]=='=')
printf("\nNot Equal");
else
printf("\n Bit Not");
break;
case'&':
if(s[1]=='&')
22
printf("\nLogical AND");
else
printf("\n Bitwise AND");
break;
case'|':
if(s[1]=='|')
printf("\nLogical OR");
else
printf("\nBitwise OR");
break;
case'+':
printf("\n Addition");
break;
case'-':
printf("\nSubstraction");
break;
case'*':
printf("\nMultiplication");
break;
case'/':
printf("\nDivision");
break;
case'%':
printf("Modulus");
break;
default:
printf("\n Not a operator");
}
getch();
}
23
OUTPUT:
RESULT:
Thus the program for the exercise on the syntax using YACC has been executed
successfully and Output is verified.
24
Ex No:5 PROGRAM TO RECOGNISE A VALID VARIABLE WHICH
STARTS WITH A LETTER FOLLOWED BY ANY NUMBER OF
Date: LETTERS OR DIGITS
PROGRAM :
variable_test.l
%{
/* This LEX program returns the tokens for the Expression */
#include "y.tab.h"
%}
%%
"int " {return INT;}
"float" {return FLOAT;}
"double" {return DOUBLE;
}
[a-zAZ][0-9]
{
printf("\nIdentifier is %s",yytext);
return ID;
}
return yytext[0];
\n return 0;
int yywrap()
{
return 1;
}
25
variable_test.y%
{
#include
/* This YACC program is for recognising the Expression*/
%}
%token ID INT FLOAT DOUBLE
%%
D;T L;
L:L,ID
|ID;
T:INT|FLOAT|DOUBLE;
%% extern FILE *yyin;
main()
{
do
{
yyparse();
}while(!feof(yyin);
}
yyerror(char*s)
{
}
26
OUTPUT:
RESULT:
Thus the program for the exercise on the syntax using YACC has been executed
successfully and Output is verified.
27
Ex No:6
Date:
IMPLEMENTATION OF CALCULATOR USING LEX AND YACC
PROGRAM:
%{
#include<stdio.h>
int op=0,i;
float a,b;
%}
dig[0-9]+|([0-9]*)"."([0-9]+)
add "+" sub "-" mul"*" div "/" pow "^" ln \n%%
{dig}{digi();}
{add}{op=1;}
{sub}{op=2;}
{mul}{op=3;}
{div}{op=4;}
{pow}{op=5;}
{ln}{printf("\n the result:%f\n\n",a);
}
%% digi()
{
if(op==0)
a=atof(yytext);
else {
b=atof(yytext);
switch(op) {
28
case 1:a=a+b;
break;
case 2:a=a-b;
break;
case 3:
a=a*b;
break; case
4:a=a/b;
break;
case 5:
for(i=a;b>1;b--)
a=a*i;
break;
}
op=0;
}}
main(int argv,char *argc[])
{
yylex();
}
yywrap()
{
return 1;
}
29
OUTPUT:
Lex cal.l Cc
lex.yy.c-ll a.out
4*8
The result is : 32
RESULT:
Thus the program for the exercise on the syntax using YACC has been
executedSuccessfully and Output is verified.
30
Ex No:7 CONVERT THE BNF RULES INTO YACC FORM AND WRITE
Date: CODE TO GENERATE ABSTRACT SYNTAX TREE USING AND
YACC.
AIM:
INTRODUCTION:
BNF-Backus Naur form is formal notationfor encoding grammars intended for human
ALGORITHM:
32
op[5];
char arg1[10];
char arg2[10];
char result[10];
}QUAD[30];
struct stack
{ int
items[100]; int
top;
}stk; int
Index=0,tIndex=0,StNo,Ind,tInd;
extern int LineNo;
%}
%union
{ char var[10];
}
%token <var> NUM VAR RELOP
%token MAIN IF ELSE WHILE TYPE
%type <var> EXPR ASSIGNMENT CONDITION IFST
ELSEST WHILELOOP
%left '-' '+'
%left '*' '/'
%%
PROGRAM : MAIN BLOCK;
BLOCK: '{' CODE '}';
CODE: BLOCK| STATEMENT CODE| STATEMENT;
STATEMENT: DESCT ';'| ASSIGNMENT ';'| CONDST| WHILEST;
DESCT: TYPE VARLIST;
VARLIST: VAR ',' VARLIST| VAR;
ASSIGNMENT: VAR '=' EXPR
{
strcpy(QUAD[Index].op,"=");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,$1);
strcpy($$,QUAD[Index++].result);
};
EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$);}| EXPR '-' EXPR {AddQuadruple("-",
$1,$3,$$);}| EXPR '' EXPR { AddQuadruple("",$1,$3,$$);}| EXPR '/' EXPR { AddQuadruple("/",
$1,$3,$$);}| '-' EXPR { AddQuadruple("UMIN",$2,"",$$);}| '(' EXPR ')' {strcpy($$,$2);}| VAR|
NUM;
CONDST: IFST{ Ind=pop(); sprintf(QUAD[Ind].result,"%d",Index);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
33
| IFST ELSEST
;
IFST: IF '(' CONDITION ')'
{
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"- 1"); push(Index);
Index++;
}
BLOCK { strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"- 1");
push(Index);
Index++;
};
ELSEST: ELSE{
tInd=pop(); Ind=pop();
push(tInd); sprintf(QUAD[Ind].result,"%d",Index);
}
BLOCK{ Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
};
CONDITION: VAR RELOP VAR {AddQuadruple($2,$1,$3,$$);
StNo=Index- 1;
}| VAR| NUM;
WHILEST: WHILELOOP{ Ind=pop();
sprintf(QUAD[Ind].result,"%d",StNo);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
};
WHILELOOP: WHILE '(' CONDITION ')' {
strcpy(QUAD[Index].op,"=="); strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"- 1"); push(Index);
Index++;
} BLOCK {
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"- 1"); push(Index);
Index++;
}
; %% extern FILE *yyin; int
34
main(int argc,char *argv[])
{ FILE *fp; int i; if(argc>1)
{ fp=fopen(argv[1],"r");
if(!fp) { printf("\n File not
found"); exit(0); } yyin=fp; }
yyparse();
printf("\n\n\t\t ---------------------""\n\t\tPos Operator Arg1 Arg2 Result" "\n\t\t --------------------");
for(i=0;i<Index;i++)
{
printf("\n\t\t %d\t %s\t %s\t %s\t%s",i,QUAD[i].op,QUAD[i].arg1,QUAD[i].arg2,QUAD[i].result);
printf("\n\t\t -----------------------");
printf("\n\n");
return 0;
}
void push(int data)
{
stk.top++;
if(stk.top==100)
{
printf("\n Stack overflow\n");
exit(0);
}
stk.items[stk.top]=data;
}
int pop()
{
int data;
if(stk.top==- 1)
{
printf("\n Stack underflow\n");
exit(0);
}
data=stk.items[stk.top return data;
}
void AddQuadruple(char result[10])
{ strcpy(QUAD[Index].op,op);
strcpy(QUAD[Index].arg1,arg1);
strcpy(QUAD[Index].arg2,arg2);
strcpy(result,QUAD[Index++].result);
} yyerror()
{ printf("\n Error
}
Input: $vi test.c main()
{
int a,b,c; if(a<b) { a=a+b; } while(a<b)
35
{ a=a+b; } if(a<=b)
{ c=a- b;
}
op[5],char arg1[10],char--];
sprintf(QUAD[Index].result,"t%d",tIndex++);
on line no:%d",LineNo);
arg2[10],char
else
{
c=a+b;
}
}
OUTPUT:
36
$ lex int.l
$ yacc –d int.y
$ ./a.out test.c
RESULT:
Thus the program for the exercise on the syntax using YACC has been executed
successfully and output is verified.
37
Ex No:8 IMPLEMENT CONTROL FLOW ANALYSIS AND DATA FLOW
Date: ANALYSIS
AIM:
INTRODUCTION:
Data flow analysis is a technique for gathering information about the possible set of
value calculated at various points in a computer program.
Control flow analysis can be represent by basic blocks. It depicts how th program
control is being passed among the blocks.
ALGORITHM:
38
f. Delnode(x)
g. Return
6. Display the values
7. Stop the program
40
OUTPUT:
RESULT:
Thus the C program to implement data flow and control flow analysis was
executed successfully.
41
Ex No:9 IMPLEMENT ANY ONE STORAGE ALLOCATION
Date: STRATEGIES (HEAP,STACK,STATIC)
AIM:
To write a C program for Stack to use dynamic storage allocation.
INTRODUCTION:
Storage Allocation
Runtime environment manages runtime memory requirements for the following entities:
Code: It is known as the part of a program that does not change at runtime. Its
memory requirements are at the compile time
Procedures: Their text part is static but they are called in a random manner. That is
why, stack storage is used to manage procedure calls and activations.
Variables: Variables are known at the runtime only, unless they are global or constant.
Heap memory allocation scheme is used for managing allocation and de-allocation of
memory for variables in runtime.
ALGORITHM:
1. Start the program
2. Enter the expression for which intermediate code is to be generated
3. If the length of the string is greater than 3, than call the procedure to return the
precedence
4. Among the operands.
5. Assign the operand to exp array and operators to the array.
6. Create the three address code using quadruples structure.
7. Reduce the no of temporary variables.
8. Continue this process until we get an output.
9. Stop the program.
42
PROGRAM: (STACK TO USE DYNAMIC STORAGE ALLOCATION)
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
struct node
{
int label;
struct node *next;
}
void main() { int ch = 0; int k;
struct node h, *temp, *head; head = (struct node) malloc(sizeof(struct node));
head->next = NULL;
while(1)
{
printf("\n Stack using Linked List \n");
printf("1->Push ");
printf("2->Pop ");
printf("3->View");
printf("4->Exit \n");
printf("Enter your choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d", &temp->label);
h = head; temp->next = h->next; h->next = temp;
break;
case 2:
h = head->next;
head->next = h->next;
printf("Node %s deleted\n", h->label);
free(h);
break;
case 3:
printf("\n HEAD -> ");
h = head;
while(h->next != NULL)
{
h = h->next; printf("%d -> ",h->label);
}
printf("NULL \\n");
43
break;
case 4:
exit(0);
}
}
}
44
OUTPUT:
RESULT:
Thus the program for implement storage allocation to use dynamic process for
stack has been successfully executed.
45
Ex No:10
Date: CONSTRUCTION OF DAG
AIM:
To write a C program to construct of DAG(Directed Acyclic Graph)
INTRODUCTION:
The code optimization is required to produce an efficient target code. These are two important
issues that used to be considered while applying the techniques for code optimization.
They are:
The semantics equivalences of the source program must not be changed.
The improvement over the program efficiency must be achieved without changing the
algorithm.
ALGORITHM:
#include<stdio.h>
main()
{
struct da
{
int ptr,left,right;
char label;
46
}
dag[25];
int ptr,l,j,change,n=0,i=0,state=1,x,y,k;
char store,*input1,input[25],var;
clrscr();
for(i=0;i<25;i++)
{
dag[i].ptr=NULL;
dag[i].left=NULL;
dag[i].right=NULL;
dag[i].label=NULL;
}
printf("\n\nENTER THE EXPRESSION\n\n");
scanf("%s",input1);
/*EX:((a*b-c))+((b-c)*d)) like this give with paranthesis.limit is 25 char ucan change that*/
for(i=0;i<25;i++) input[i]=NULL;
l=strlen(input1);
a:for(i=0;input1[i]!=')';i++)
for(j=i;input1[j]!='(';j--);
for(x=j+1;x<i;x++)
if(isalpha(input1[x]))
input[n++]=input1[x];
else
if(input1[x]!='0')
store=input1[x];
input[n++]=store;
for(x=j;x<=i;x++)
input1[x]='0';
if(input1[0]!='0')
47
goto a;
for(i=0;i<n;i++)
{
dag[i].label=input[i]; dag[i].ptr=i;
if(!isalpha(input[i])&&!isdigit(input[i]))
{
dag[i].right=i-1;
ptr=i;
var=input[i-1];
if(isalpha(var))
ptr=ptr-2;
else
{
ptr=i-1;
b:
if(!isalpha(var)&
&!isdigit(var))
{
ptr=dag[ptr].left;
var=input[ptr];
goto b;
}
else
ptr=ptr-1;
}
dag[i].left=ptr;
}}
printf("\n SYNTAX TREE FOR GIVEN EXPRESSION\n\n");
printf("\n\n PTR \t\t LEFT PTR \t\t RIGHT PTR \t\t LABEL\n\n");
48
for(i=0;i<n;i++)
/* draw the syntax tree for the following output with pointer value*/
printf("\n%d\t%d\t%d\t%c\n",dag[i].ptr,dag[i].left,dag[i].right,dag[i].la bel);
getch();
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if((dag[i].label==dag[j].label&&dag[i].left==dag[j].left)&&dag[ i].right==dag[j].right)
{
for(k=0;k<n;k++)
{
if(dag[k].left==dag[j].ptr)dag[k].left=dag[i].ptr;
if(dag[k].right==dag[j].ptr)dag[k].right=dag[i].ptr;
}
dag[j].ptr=dag[i].ptr;
}
} } printf("\n DAG FOR GIVEN EXPRESSION\n\n");
printf("\n\n PTR \t LEFT PTR \t RIGHT PTR \t LABEL \n\n");
for(i=0;i<n;i++)
/*draw DAG for the following output with pointer value*/
printf("\n %d\t\t%d\t\t%d\t\t%c\n",dag[i].ptr,dag[i].left,dag[i].right,dag[i].label);
getch();
}
49
OUTPUT:
RESULT:
Thus the program for implementation of DAG has been successfully executed and output
is verified.
50
Ex No:11
Date: IMPLEMENT THE BACK END OF THE COMPILER
AIM:
To implement the back end of the compiler which takes the three address code and
produces the 8086 assembly language instructions that can be assembled and run using a
8086 assembler. The target assembly instructions can be simple move, add, sub, jump.
Also simple addressing modes are used.
INTRODUCTION:
BACK END:
Some local optimization
Register allocation
Peep-hole optimization
Code generation
Instruction scheduling
The main phases of the back end include the following:
Analysis: This is the gathering of program information from the intermediate
representation derived from the input; data-flow analysis is used to build use-define
chains, together with dependence analysis, alias analysis, pointer analysis, escape
analysis etc.
Optimization: The intermediate language representation is transformed into
functionally equivalent but faster (or smaller) forms. Popular optimizations are
expansion, dead, constant, propagation, loop transformation, register allocation and
even automatic parallelization.
51
Code generation: The transformed language is translated into the output language,
usually the native machine language of the system. This involves resource and storage
decisions, such as deciding which variables to fit into registers and memory and the
selection and scheduling of appropriate machine instructions along with their
associated modes. Debug data may also need to be generated to facilitate debugging.
ALGORITHM:
4. Write the generated code into output definition of the file in outp.c
5. Print the output.
#include<stdio.h>
#include<stdio.h>
//#include<conio.h>
#include<string.h>
void main()
{
char icode[10][30],str[20],opr[10];
int i=0;
//clrscr();
printf("\n Enter the set of intermediate code (terminated by exit):\n");
do
{
scanf("%s",icode[i]);
52
}
while(strcmp(icode[i++],"exit")!=0);
printf("\n target code generation");
printf("\n**"); i=0;
do
{
strcpy(str,icode[i]); switch(str[3])
{
case '+':
strcpy(opr,"ADD");
break;
case '-':
strcpy(opr,"SUB");
break;
case '*':
strcpy(opr,"MUL");
break;
case '/':
strcpy(opr,"DIV");
break;
}
printf("\n\tMov %c,R%d",str[2],i);
printf("\n\t%s%c,R%d",opr,str[4],i);
printf("\n\tMov R%d,%c",i,str[0]);
}
while(strcmp(icode[++i],"exit")!=0);
//getch();
}
53
OUTPUT:
RESULT:
Thus the program was implemented to the TAC has been successfully executed.
54
Ex No:12
Date:
IMPLEMENTATION OF SIMPLE CODE OPTIMIZATION
TECHNIQUES
AIM:
INTRODUCTION:
The output code must not, in any way, change the meaning of the program.
Optimization should increases the speed of the program and if possible, the program
should demand less number of resources.
Optimization should itself be fast and fast and should not delay the overall compiling
process.
Efforts for an optimized code can be made at various levels of compiling the process.
At
the beginning, users can change/rearrange the code or use better algorithms to write
the code.
After generating intermediate code, the compiler can modify the intermediate code by
address calculations and improving loops.
While producing the target machine code, the compiler can make use of memory
hierarchy and cpu registers.
Optimization can be categorized broadly into two types: Machine independent and
Machine dependent.
In this optimization, the compiler takes in the intermediate code and transforms a part of
the code that does not involve any CPU registers and/or absolute memory locations.
55
For Example:
do
{ item=10;
value=value+item;
This code involves repeated assignment of the identifier item, which if we put this way:
item=10;
do
value=value+item;
}while(value<100)
Should not only save the cpu cycles, but can be used on any processor.
Machine dependent optimization is done after the target code has been generated and
when the code is transformed according to the target machine architecture. It involves
CPU registers and may have absolute memory references rather than relative references.
Machinedependent optimizers put efforts to take maximum advantage of memory
hierarchy.
ALGORITHM:
56
PROGRAM: (SIMPLE CODE OPTIMIZATION TECHNIQUE)
Before:
Using for :
#include<iostream.h>
#include <conio.h>
int main()
int i, n;
int fact=1;
for(i=n;i>=1;i--)
0;
57
OUTPUT:
58
After: (SIMPLE CODE OPTIMIZATION TECHNIQUE)
Using do-while:
#include<iostream.h>
#include<conio.h>
void main()
{
f=f*n; n--;
while(n>0);
getch();
OUTPUT:
59
RESULT:
60