0

I am trying to write a code for a problem in C. The code is as follows:

#include<stdio.h>
int cop(int a,int b)
{
    int c,d,e,f,g;
    if(a>b)
    {   
        c=a;
        a=b;
        b=c;
    }
    while(c!=0)
    {
        c=b%a;
        b=a;
        a=c;
    }
    return b;
}

int main()
{
    int i=1, j=1, k, a, b, c, d, e, f, g=1;

    scanf("%d",&k);
    int q=0;
    for(q=k;q>0;q--)
    {
        scanf("%d",&a);
        while(g==1)
        {
            b=j+i;
            i=j;
            j=b;
            g=cop(j,a);
            printf("%d\n",g);
        }
        printf("%d %d\n",g,j);
        j=1;i=1;g=1;
    }

return 0;
}       

When I give input as 3 3 5 161 it was printing

1
3
3 3
1
1
5
5 5
1
1
1
1
1
7
7 21

and when i comment out the statement printf("%d\n",g) and execute with the same input i get the output as follows:

3 3
5 3
161 3

So, my doubt is why I am not getting:-

3 3
5 5
7 21
5
  • So what do you want to do exactly? I cannot understand by just reading your code. And I got a different result when inputing 3 3 5 161.
    – halfelf
    Commented Oct 8, 2012 at 13:27
  • It sounds like you should run your code with a debugger attached. Commented Oct 8, 2012 at 13:29
  • oh you think printf distorted your output some how? or you wrote your logic incorrectly? which is it?
    – Prasanth
    Commented Oct 8, 2012 at 13:32
  • 1
    You cannot "doubt" something that you don't understand. Perhaps you can "be puzzled by" it, but you're certainly not in a position to doubt it.
    – Kerrek SB
    Commented Oct 8, 2012 at 13:37
  • Always compile with warnings enabled. Commented Oct 8, 2012 at 13:53

1 Answer 1

7
foo.c: In function 'cop':
foo.c:4: warning: 'c' may be used uninitialized in this function

Does this help?

You're depending on an uninitialized value in your function (in some cases). This means that the extra call to printf could dirty a register or a stack value and that will change how your function behaves.

Strictly speaking it's an undefined behavior and you just got a lesson on how undefined behavior can look like - unrelated function calls change how the undefined behavior behaves.

Not the answer you're looking for? Browse other questions tagged or ask your own question.