[Solved] Convert code from C++ to C: `a+b > b+a` where a and b are `string`


This will do what you expect without any concatenation:

int compare(char *a, char *b)
{
    char *p1, *p2;
    int i, len = strlen(a) + strlen(b);

    p1 = a;
    p2 = b;
    for (i=0;i<len;i++) {
        if (*p1 > *p2) {
            return 1;
        } else if (*p1 < *p2) {
            return -1;
        }
        p1++;
        p2++;
        if (!*p1) {
            p1 = b;
        }
        if (!*p2) {
            p2 = a;
        }
    }
    return 0;
}

The pointers p1 and p2 start at the beginning of a and b respectively and compare character by character for each one, then each pointer is incremented if there’s no difference. When either pointer encounters a null byte, it is reassigned to the start of the other variable to continue from there.

We start by getting the combined length of the two strings and run through the loop that many times.

Working on the decimal representation of the two numbers as strings is actually simpler than dealing with them as integers, as the latter would involve determining the number of decimal digits and multiplying accordingly. This method also isn’t constrained by the bounds of whatever integer type you may be using.

solved Convert code from C++ to C: `a+b > b+a` where a and b are `string`