How to implement the equal algorithm to check whether two integer ranges are equal in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

/*
    equal:
    Checks whether two integer ranges are equal.

    C uses memcpy/memcmp for raw memory comparison because:
        - memcmp is optimized in all standard C libraries
        - It compares bytes efficiently
        - It avoids manual loops unless needed

    Parameters:
        a, b  - pointers to the two arrays
        n     - number of elements to compare

    Returns:
        true  if arrays contain identical elements in identical order
        false otherwise
*/
bool equal(const int *a, const int *b, size_t n) {
    /* memcmp compares raw bytes; multiply by sizeof(int) */
    return memcmp(a, b, n * sizeof(int)) == 0;
}

int main(void) {
    int x[] = {1, 2, 3, 4, 5};
    int y[] = {1, 2, 3, 4, 5};
    int z[] = {1, 2, 3, 9, 5};

    size_t n = sizeof(x) / sizeof(x[0]);

    /* Compare x and y */
    bool xy_equal = equal(x, y, n);
    printf("x and y equal? %s\n", xy_equal ? "true" : "false");

    /* Compare x and z */
    bool xz_equal = equal(x, z, n);
    printf("x and z equal? %s\n", xz_equal ? "true" : "false");

    return 0;
}



/*
run:

x and y equal? true
x and z equal? false

*/

 



answered Jul 26 by avibootz

Related questions

3 answers 432 views
...