0

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.

  • 1
    nice file name. is this the exact code, without main function etc.? if you copy pasted the whole file, it might have been more helpful – Hayri Uğur Koltuk Jan 10 '19 at 20:00
  • 5
    You need a `main` function, you can not call `Swap` in global scope. – David Ranieri Jan 10 '19 at 20:01
  • Thank you guys and yes, this is the exact copy. The example is devoid of a main() function and it is not specified anywhere that i should be using it to call functions, at least not as far as i am in the book. – spaghettiBox Jan 10 '19 at 20:17

1 Answers1

2
#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

bruno
  • 32,421
  • 7
  • 25
  • 37
  • This has in fact worked. I wonder why this was not specified in the book... – spaghettiBox Jan 10 '19 at 20:14
  • @spaghettiBox: Usually, you see the function definition, followed by text that says something like *"You use this function thus:"*, and then the usage example. The idea is that the function definition is the code you add to your own program or library, and the use example shows how you *can* use it. It is not intended to be a self-contained example *program*. If you want a self-contained example program from such examples, you do exactly what bruno did here. So, you can think of this approach as shorthand; omitting the always-same "red tape". – Nominal Animal Jan 10 '19 at 21:02
  • Nominal Animal very well said, i'm simply used to being held by my hand and walked through the steps. I will look at this book differently henceforth. – spaghettiBox Jan 11 '19 at 04:40