user11224591
user11224591

Reputation:

Why is it OK to pass mismatch argument into isdigit function?

I'm new to C, sorry if my question is a little bit strange.

the signature of isdigital function is:

int isdigit(int arg);

but I saw a lot of cases that a char can also be argument, for example:

char c = '5';
printf("Result when numeric character is passed: %d", isdigit(c));

c is a char, not an interger, how can it can be used in this way? does implicit casting from char to int occur here?

Upvotes: 1

Views: 140

Answers (1)

chux
chux

Reputation: 153457

c is a char, not an integer, how can it can be used in this way?

The char is converted to an int. When char is signed, this is no problem - the value converts without issue.

When char is unsigned, except on rare machines, again no issue as all values of unsigned char exist in int.

Th trick is that is...(int) functions are well defined for int values in the unsigned char range and EOF (some negative value), but not all negative values. Best for char to be cast to the unsigned char first.

char c = '5';
// printf("Result when numeric character is passed: %d", isdigit(c));
printf("Result when numeric character is passed: %d", isdigit((unsigned char) c));

Note: the return value of isdigit(int) and friends are zero (not a digit) or some non-zero value (is a digit). The exact non-zero value is not so important as much as it is non-zero (true).

does implicit casting from char to int occur here?

No, type conversion occurs.

Upvotes: 1

Related Questions