Home > front end >  C programming: Use of undeclared identifier
C programming: Use of undeclared identifier

Time:01-10

I'm trying to run a swap algorithm and return the values in c. Please help!

void swap(int a,int b)
{
    temp = a;
    a=b;
    b=temp;
}

void display()
{
    return a, b
}

void main()
{
    x=10
    y=12
    swap(a,b)
    display()
}
error: use of undeclared
      identifier 'x'       
error: 'main' must return
      'int'                 

I added void to the function names and int to the swap parameters and I'm not sure what else to do.

CodePudding user response:

There are a lot of error in this program. In c programming, before using a variable, we must explicitly declare the type of data that it can store. So you must define the type of x and y to integer type (int x = 10,int y=12). The next thing is that you are passing undefined identifiers a and b in swap(). It must be swap(x,y). The final thing is that when you return a value from a function you must define the return type of the function to the particular type that you are returning. In this case the return type of the function must be int display().

CodePudding user response:

1.) In C, statements end with semi-colons (;). You are missing semi-colons on most of your lines.

2.) C is "pass-by-copy", when you pass a and b to the swap function, the variables are copied, and changes are not visible in the calling function. You must pass-by-reference (aka pointer) so that local changes inside the function will be visible to the caller.

I've tried to fix up your code with extensive comments below.
But frankly, your code is a MESS.
Read a basic C tutorial. These issues are covered everywhere by basic tutorials.

// Changed to pointer notation for pass-by-reference
void swap(int*const a,int*const b)
{
    // ERROR: temp = a; temp is not defined
    int temp = *a;
    // Declared temp as int. Assigned it to the value of pointer a.

    *a=*b;
    // Used pointer/de-reference notation, so that changes are visible to the caller.
    *b=temp;
}

void display(int a, int b)
{
    // return a, b
    // This line makes no sense.

    printf("Values %d and %d\n", a, b);
    // Use printf to display data.
}

int main(void) // Main always returns int in C
{
    // BAD x=10. Corrected:
    int x = 10;

    // BAD y=12. Corrected:
    int y = 12;

    swap(&x,&y);
    // Added a semi-colon.
    // a and b are not defined. Changed to x, y

    display(x, y);
    // Added a semi-colon.
    // Passed parameters x and y to be displayed.
}

Code fixed up and running online:

https://ideone.com/d581y3

  • Related