Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char Comparison in C

Tags:

c

comparison

char

I'm trying to compare two chars to see if one is greater than the other. To see if they were equal, I used strcmp. Is there anything similar to strcmp that I can use?

like image 345
dclark Avatar asked Mar 29 '14 20:03

dclark


People also ask

Can you compare char in C?

Compare Char in C Using the strcmp() Function in C The strcmp() function is defined in the string header file and used to compare two strings character by character. If both strings' first characters are equal, the next character of the two strings will be compared.

Can you use == for char?

Yes, char is just like any other primitive type, you can just compare them by == .


2 Answers

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are almost always ASCII codes, but other encodings are allowed. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as this on an ASCII system.

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

Note that even if ASCII is not required, this function will work because C requires that the digits are in consecutive order:

int isdigit(char c) {
    if(c >= '0' && c <= '9') 
        return 1;
    return 0;
} 
like image 103
Victor Avatar answered Oct 20 '22 00:10

Victor


In C the char type has a numeric value so the > operator will work just fine for example

#include <stdio.h>
main() {

    char a='z';

    char b='h';

    if ( a > b ) {
        printf("%c greater than %c\n",a,b);
    }
}
like image 12
Vorsprung Avatar answered Oct 20 '22 02:10

Vorsprung