I am writing a lex program. I have initialized 3 char pointers. And then I am defining them to tokens if they satisfy the criteria. But when I print them afterwards, the first prints value of all 3, second of last two and last of itself. Why is this happenning? Here is my code:
%{
#include<stdio.h>
#include<string.h>
int for_cond = 0;
char *cond1, *cond2, *cond3;
char * for_body = "";
//char * loop = "";
%}
VAR [a-zA-Z_]+[a-zA-Z0-9_]*
%%
for[ ]*\( {for_cond++;}
int[ ]+{VAR}[ ]*\=[ ]*[0-9]+ {if(for_cond==1){cond1 = yytext;}else if(for_cond==4){for_body = strcat(for_body,yytext);}}
; {if(for_cond==1||for_cond==2){for_cond++;} else if(for_cond==4){for_body = strcat(for_body,yytext);}}
{VAR}[ ]*(\<|\>|\<\=|\>\=|\=\=)[ ]*[0-9]+ {if(for_cond==2){cond2 = yytext;}else if(for_cond==4){for_body = strcat(for_body,yytext);}}
{VAR}[ ]*((\+\+|\-\-)|((\+\=|\-\=|\*\=|\/\=)[ ]*({VAR}|[0-9]+))) {if(for_cond==3){cond3 = yytext;}else if(for_cond==4){for_body = strcat(for_body,yytext);}}
%%
int yywrap(void){}
int main(){
yylex();
printf("cond1 = %s\ncond2 = %s\ncond3 = %s\n", cond1, cond2, cond3);
return 0;
}
example input:
for(int i=0;i<=2;i++)
expected output:
cond1 = int i=0
cond2 = i<=2
cond3 = i++
What I am getting:
cond1 = int i=0;i<=2;i++)
cond2 = i<=2;i++)
cond3 = i++)
Why is this happenning? How do I fix this?