0

I just started attending an C basic course. Today I had this problem.

Why does entering Y and N with the "OutputF()"-function yield different results as passing Y an N directly?

printf("%d", OutputF(InputF(), InputF()));
printf("%d", OutputF('Y', 'N'));

Here is the whole code:

#include<stdio.h>

char InputF(void) {
    char a = getchar();
    while (getchar() != '\n');
    return a;
}

int OutputF(char Input1, char Input2) {
    if (Input1 == 'y' || Input1 == 'Y')
        if (Input2 == 'y' || Input2 == 'Y')
            return 200;
        else
            return 300;
    else
        if (Input2 == 'y' || Input2 == 'Y')
            return 400;
        else
            return 500;
}


int main(void)
{
    printf("%d", OutputF(InputF(), InputF()));
    printf("%d", OutputF('Y', 'N'));
    return 0;
}

2 Answers2

1

You are assuming that OutputF(InputF(), InputF()) is calling InputF() in the order declared in the function call parameters. That is undefined behavior in C. From the C specification:

The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.

The compiler can do whatever it wants. Try this instead:

int main(void)
{
    char in1 = InputF();
    char in2 = InputF();

    printf("%d\n", OutputF(in1,in2));
    printf("%d\n", OutputF('Y', 'N'));
    return 0;
}

See this link for more details on undefined behaviors

OldProgrammer
  • 12,050
  • 4
  • 24
  • 45
0

The reason is when you call the function Input (printf("%d", OutputF(InputF(), InputF()));), you can see in the debugger that Input1 will be 'Y' and Input2 will be 'N'. And on you second call is opposite, that the reason for the diffrent output the first is 400 and the second is 300.

First call(while entering 'Y' first and 'N' second):

    Input1  78 'N'  char
    Input2  89 'Y'  char

Output is 400.

Second call:

    Input1  89 'Y'  char
    Input2  78 'N'  char

Output is 300.

ValeriF21
  • 454
  • 1
  • 3
  • 14