i have a code to check lexeme is keyword or not:

void Is_Keyword_Or_Not()
            {
                 char *keywords[]={"INCLUDE","VOID","MAIN","i","var","cin","cout","if",
		  "then","else","and","or","not","loop","exit","when",
		  "while","until"};
              int j=0;
             flag=0;
              for (j=0;j<18;j++)         //search for keyword & # of keywords = 18.
              {
                if (strcmpi(lexeme,keywords[j])==0)
            	{
            		temp.assign(lexeme,INCLUDE);
            		flag=1;
            		break;
            	}
              } 
            }

i have defined macros like:
INCLUDE 1
INT 2
etc

just like INCLUDE in temp.assign,i want specific value defined in macro to be returned as compared to lexeme

it could be done by using lots of "if" but is there another short way to do that?

MACROs are evil! Don't use them. From the looks of it, that you need is a look-up table. If you are restricted to C, from the looks of your code that is the case, then you can do this:

struct myKeyword {
  const char name[];
  int ID;
};

myKeyword *keywords = {{"INCLUDE",1},{"INT",2},...};

void IsKeywordOrNot() {
  int j=0;
  flag=0;
  for (j=0;j<18;j++) //search for keyword & # of keywords = 18.
  {
    if (strcmpi(lexeme,keywords[j].name)==0)
    {
      temp.assign(lexeme,keywords[j].ID);
      flag=1;
      break;
    };
  };
};

Another thing that is evil are global variables (like keywords, flag, lexeme), so try to pass them as parameters to the function instead and not make them global variables.

If you are not restricted to C, but can use C++ syntax and STL containers. I would suggest you use std::map instead:

#include <map>
#include <string>

std::map<std::string,int> keywords;
void initKeywords() {
  keywords["INCLUDE"] = 1;
  keywords["INT"] = 2;
  ...
};

void IsKeywordOrNot(int& flag, std::string& lexeme) {
  if(keywords.size() == 0) 
    initKeywords();
  int j=0;
  flag=0;
  std::map<std::string,int>::iterator iter = keywords.find(lexeme);
  if(iter != keywords.end()) {
    temp.assign(lexeme.c_str(),iter->second);
    flag = 1;
  };
};

thanks a lot
this will definately help me

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.