Search code examples
cpass-by-referencecs50swapfunction-definition

I need help understanding how to fix this: expected expression swap_numbers(int first_num, int second_num);


I am having trouble figuring out what I did wrong here. Im not sure what expression the compiler is needing. This is the error: expected expression swap_numbers(int first_num, int second_num);

I have tried googling this error but most of the answers say that I didnt declare it. However, I thought i did declare it when i included the cs50 library. For clarity, I am in the cs50x class at harvard and I have heard in the past that this library is class specific, so I tried running this in our compiler in class and it still says this.

#include <cs50.h>

#include <stdio.h>

int swap_numbers(int first_num, int second_num);

int main(void)

{

  int first_num = get_int("Input 1st number:\n");

  int second_num = get_int("Input 2nd number:\n");

  swap_numbers(int first_num, int second_num);

  printf("First_num = %i\n", first_num);
  printf("Second_num = %i\n", second_num);
}

int swap_numbers(int first_num, int second_num)

{

  int temp_num = second_num;

  first_num = temp_num;

  second_num = first_num;
}

Solution

  • This record

    swap_numbers(int first_num, int second_num);
    

    is not a function call. You have to write at least like

    swap_numbers( first_num, second_num);
    

    Also the function does not swap the objects first_num and second_num defined in main because it deals with copies of values of the objects.

    Also after these lines within the function

    int temp_num = second_num;
    
    first_num = temp_num;
    

    the value of the variable first_num is lost. Thus in the next statement

    second_num = first_num;
    

    the variable second_num is assigned by itself.

    And the function has the return type int but returns nothing.

    To swap the original variables you need to pass them to the function by reference.

    In C passing by reference means passing objects indirectly through pointers to them.

    So the function should be declared and defined like

    void swap_numbers( int *first_num, int *second_num )
    {
        int temp_num = *second_num; 
        *second_num = *first_num;
        *first_num = temp_num;
    }
    

    and the function is called like

    swap_numbers( &first_num, &second_num );