Can someone tell me why my compiler won't compile this code and how to fix it?

void gcd(int x, int y)
{
    if (x > y)
    {
        int c;
        while(1)
        {
            c = x % y;
            return y;
            x = y;
            y = c;
        }
    if (y > x)
    {
        int d;
        while(1)
        {
            d = x % y;
            return x;
            y = x;
            x = d;
        }

    }
}

Recommended Answers

All 7 Replies

what are the error message(s) ?

lines 9 and 19: why did you stick those returns in the middle of those if statements? That makes line 10, 11, 20 and 21 unusable because they can never be executed.

Mising } between lines 12 and 13.

what are the error message(s) ?

lines 9 and 19: why did you stick those returns in the middle of those if statements? That makes line 10, 11, 20 and 21 unusable because they can never be executed.

Mising } between lines 12 and 13.

Here's the full code. I just didn't want to show it all since I know the main is really incomplete right now.

#include <stdio.h>

void gcd(int x, int y)
{
    if (x > y)
    {
        int c;
        while(1)
        {
            c = x % y;
            x = y;
            y = c;
            return y;
        }
    }
    if (y > x)
    {
        int d;
        while(1)
        {
            d = x % y;
            y = x;
            x = d;
            return x;
        }

    }
}

int main (void)
{
    printf("Please enter a value for x:\n");

    printf("x: ");
    scanf("%d" , &x);

    printf("Please enter a value for y:\n");

    printf("y: ");
    scanf("%d" , &y);

    printf("gcd of x and y  %d and %d\n", x, y);


    return 0;
}

I added the brace in between those 2 lines you said.

I didn't know those lines would become unusable. I fixed it.

I forgot to add the errors.
gcd.c: In function 'gcd':
gcd.c:13: warning: 'return' with a value, in function returning void
gcd.c:24: warning: 'return' with a value, in function returning void
gcd.c: In function 'main':
gcd.c:35: error: 'x' undeclared (first use in this function)
gcd.c:35: error: (Each undeclared identifier is reported only once
gcd.c:35: error: for each function it appears in.)
gcd.c:40: error: 'y' undeclared (first use in this function)

Do you know what a void function is? Do you know what it returns?

Do you know what a void function is? Do you know what it returns?

Not really. I was told by my teacher to use void but it looks like this is causing problems.

Ahh, got it.

An integer function - int sub( ) - returns an integer
A float function - float sub( ) - returns a float
A void function - void sub( ) - returns nothing at all.

Also in the main function. You have to declare variable before using them .....

Thx both of you. What both of you said helps a lot :).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.