learner
learner

Reputation: 23

Type checking in C

I am coding the following if-statement:

if(chars[a]== char)
{
  do sth;
}

My purpose is to test if the element in chars array is a character and if so do something to it. In languages like Python, there is the type function used to find the data type. C doesn't have those. In this case, how can I do something like the above in C?

Upvotes: 0

Views: 3584

Answers (3)

Kon
Kon

Reputation: 4099

C is a statically typed language. Any variable declared to be a certain type is guaranteed to be that type at run time.

Upvotes: 0

user1683793
user1683793

Reputation: 1313

As observed elsewhere, ANYTHING in a char array is a char. If you want to see about alphas or characters check out isdigit() and isalpha().

There is a C'ism: If you want to know if a char is any from a list, say "asdfjkl" you can run

if(strchr("asdfjkl",chars[a]) != NULL  )
{
    oneOfThem();
}

The strchr function returns null if the character is not found. In this case, you don't care which one matches, just if it on the list so check for != NULL. If you are a minimalist programmer, you can also type (if(strchr()) which will do the same thing.

Upvotes: 1

AShelly
AShelly

Reputation: 35540

All the items in a character array are of type char. Perhaps you mean to check if they are printable characters, in which case you can use if (isprint(char[a])) {...}.

isprint() is defined in <ctype.h> along with other character class tests.

Based on your comment, it looks like you are looking for isalnum()

Upvotes: 2

Related Questions