Search code examples
cpointersspecifier

Swap() func in the book Essential C does not compile


wtf.c:11:6: error: expected declaration specifiers or '...' before '&' token Swap(&a, &b);

wtf.c:11:10: error: expected declaration specifiers or '...' before '&' token Swap(&a, &b);

Did not want to resort to StackOverflow for my personal problem but i cannot figure it out. The code is exactly the same as the book's. I've also tried making separated pointers and using them as arguments but i get the same error. Can someone shine some light on what am i doing wrong? I'm using gcc to compile the code.

static void Swap(int *x, int *y){
  int temp;
  temp = *x;
  *x = *y;
  *y = temp;
}

int a = 1;
int b = 2;

Swap(&a, &b);

I expected it to compile at least the exact example from the book but apparently not even that's possible.


Solution

  • #include <stdio.h>
    
    static void Swap(int *x, int *y){
      int temp;
      temp = *x;
      *x = *y;
      *y = temp;
    }
    
    int main()
    {
      int a = 1;
      int b = 2;
    
      Swap(&a, &b);
      printf("%d %d\n", a, b);
      return 0;
    }
    

    That compile and the execution print "2 1", as you can see swap works


    You had the compiler errors because of the form Swap(&a, &b); which is not a declaration nor a definition (it is a function call)

    As it is said in remark the entry point of any C program is the function main, automatically called, for more read documentation about C