📜  C程序检查“ for”循环的语法

📅  最后修改于: 2021-06-28 07:18:30             🧑  作者: Mango

如C标准所定义,for循环语法为:

for (initialisation; condition; increment/decrement)
        ... 

从句法上讲,应该有两个分号,一个是左括号,一个是右括号,并正确拼写“ for”。因此,仅检查for循环的语法,编译器要做的是检查以下条件:

  • 仅写“ for”,而不写“ For”,“ FOR”,“ foR”或其任何变体。
  • 总计语句由两个分号“;”组成在右括号“)”结束之前。
  • 在语句末尾有一个左括号“(”在“ for”关键字之后,以及一个右括号“)”。

例子:

Input : for (i = 10; i < 20 i++) 
Output : Semicolon Error

Input : for(i = 10; i < 20; i++
Output : Closing parenthesis absent at end 

代码 –

#include 
#include 
#include 
  
//array to copy first three characters of string str
char arr[3]; 
  
void isCorrect(char *str)
{
      
    //semicolon, bracket1, bracket2 are used 
        //to count frequencies of
    //';', '(', and ')' respectively
    //flag is set to 1 when an error is found, else no error
    int semicolon = 0, bracket1 = 0, bracket2 = 0, flag = 0;
      
    int i;
    for (i = 0; i < 3; i++)
        arr[i] = str[i];
          
    //first 3 characters of the for loop statement is copied
    if(strcmp(arr, "for") != 0)
    {
        printf("Error in for keyword usage");
        return;
    }
      
    //Proper usage of "for" keyword checked
    while(i != strlen(str))
    {
        char ch = str[i++];
        if(ch == '(')
        {
            //opening parenthesis count
            bracket1 ++;
        }
        else if(ch == ')')
        {
            //closing parenthesis count
            bracket2 ++;
              
        }
        else if(ch == ';')
        {
            //semicolon count
            semicolon ++;
        }
        else continue;
          
    }
      
    //check number of semicolons
    if(semicolon != 2)
    { 
        printf("\nSemicolon Error");
        flag++;
    }
      
    //check closing Parenthesis
    else if(str[strlen(str) - 1] != ')')
    { 
        printf("\nClosing parenthesis absent at end");
        flag++;
    }
      
    //check opening parenthesis
    else if(str[3] == ' ' && str[4] != '(' )
    { 
        printf("\nOpening parenthesis absent after for keyword");
        flag++;
    }
      
    //check parentheses count
    else if(bracket1 != 1 || bracket2 != 1 || bracket1 != bracket2)
    { 
        printf("\nParentheses Count Error");
        flag++;
    }
      
    //no error 
    if(flag == 0)
        printf("\nNo error");
              
}
  
int main(void) {
      
    char str1[100] = "for (i = 10; i < 20; i++)";
    isCorrect(str1);
      
    char str2[100] = "for i = 10; i < 20; i++)";
    isCorrect(str2);
      
    return 0;
}

输出 :

No error
Opening parenthesis absent after for keyword