Home > database >  I get different outputs when i use different compilers
I get different outputs when i use different compilers

Time:05-01

I was trying to solve a problem with using C. But I got different outputs in different compilers. First I tried gcc and there was no mistake but when I use clang the output changed.

PROBLEM:
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

Sample Input: 1 2 3 4 5

Sample Output: 10 14

10 = 1 2 3 4 | 14 = 2 3 4 5

The Output when I use clang: 1 14

Here is the code:

#include <stdio.h>

void  miniMaxSum(int *a, int b) {

    int sums[5] = { b, b, b, b, b };
    int min = *a, max = *a;
    for (int j = 0; j < 5; j  ) {
        sums[j] -= *(a   j);
        if (sums[j] < min)
            min = sums[j];
        if (toplamlar[j] > max)
            max = sums[j];
    }

    printf("%d %d\n", min, max);
}

int main() {

    int numbers[5] = { 0, 0, 0, 0, 0 };
    int sum;
    for (int i = 0; i < 5; i  ) {
        scanf("%d ", &numbers[i]);
        toplam  = numbers[i];
    }

    miniMaxSum(numbers, sum);

    return 0;
}

EDIT: Sorry, I changed the variables name to English sake of understanding, but I forgot the toplam (sum) and toplamlar (sums).

CodePudding user response:

Assuming you translated some of the variable names to English for non Turkish speakers, the variable sum (toplam) is uninitialized leading to undefined behavor. A common symptom for undefined behavior is different behavior on a different system / compiler.

Note that you can simplify your code by just searching for the minimum and maximum values in the array:

#include <stdio.h>

void miniMaxSum(const int *a, int sum) {
    int min = a[0], max = a[0];
    for (int j = 1; j < 5; j  ) {
        if (sums[j] < min)
            min = sums[j];
        if (sums[j] > max)
            max = sums[j];
    }
    printf("%d %d\n", sum - max, sum - min);
}

int main() {
    int numbers[5] = { 0, 0, 0, 0, 0 };
    int sum = 0;
    for (int i = 0; i < 5; i  ) {
        scanf("%d ", &numbers[i]);
        sum  = numbers[i];
    }

    miniMaxSum(numbers, sum);

    return 0;
}

CodePudding user response:

Sorry, I changed the variables name to English sake of understanding, but I forgot the toplam (sum) and toplamlar(sums).

  • Related