Michi
Michi

Reputation: 5307

Char compare Function in C

There some times when I realy need to compare two CHARs and from what I know there is no Function in C to compare two CHARs (maybe i'm wrong) and because of this I decided to write one of my own. The function is working fine but I'm not sure if is also ok, or there are some problems. I decided to ask you about this if my function is ok. Here is the program:

#include<stdio.h>
#include<string.h>

int chrcmp(const char chr1, const char chr2);

int main(void){
    char firstChar = 'a';
    char secondChar = 'a';

    if( chrcmp( firstChar, secondChar ) == 0 ){
        printf("We have a Match\n");
    }else{
        printf("There was no match Found.\n");
        printf("%c",chrcmp(firstChar, secondChar));
    }

    return 0;
}

int chrcmp(const char chr1, const char chr2){
    size_t lenght1, lenght2;

    char s1[2] = {chr1 , '\0'}; /* Convert chr1 to string */
    char s2[2] = {chr2 , '\0'}; /* Convert chr2 to string */

    lenght1 = strlen(s1); /* Store lenght of first String */
    lenght2 = strlen(s2); /* Store lenght of second String */

    if( lenght1 == 1 && lenght2 == 1){  /* Checking if both strings have the same size (1) */
        if( strcmp(s1,s2) == 0 ){     /* Compare both strings */
            return 0; /* Match Found! */
        }else{
            return 1; /*No Match!;*/
        }
    }else{
        return 1; /*To many chars Found!;*/
    }
}

If there are some problems, or if I did something wrong I have no ideeas.

Upvotes: 0

Views: 2877

Answers (3)

too honest for this site
too honest for this site

Reputation: 12263

In C, char is actually an integer type. For arithmetical operations, that is promoted to int, so you can use normal integer comparison.

Note that whether char is signed or unsigned is implementation defined, so to make sure, you should always use signed char or unsigned char (recommended) if you do arithmetics (includes comparisons) on chars other than test for equality.

What you cannot do is compare two char arrays, such as

char ch[] = "Hello";
if ( ch == "Hello" )
    ...

For that you need strncmp() or strcmp(). Use the latter only if your are absolutely sure both strings are properly terminated!

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227578

from what i know there is no Function in C to compare thow CHARs

That is incorrect. There is the equality operator == (as well as all the other comparison operators):

if (firstChar == secondChar) {
  /* chars are equal */
}

Upvotes: 3

Dai
Dai

Reputation: 155658

Uh...

Just do this:

char a = 'y';
char b = 'x';
if( a == b ) printf("Chars equal");

The char type in C (and C derivatives) is actually an integer type and has the full set of integer comparison operators defined for it: <, >, ==, !=, <=, >= in addition to the bitwise &, |, and ~ operators.

Upvotes: 3

Related Questions