Jonathan Kittell
Jonathan Kittell

Reputation: 7493

c++ function does not take 0 arguments

Why am I getting this error from the compiler about the function not taking 0 arguments? Is is because I declare the function after it has been called?

// HelloWorld.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>


using namespace std;

int main()
{
    cout << "Hello World!\n";
    cout << "Game over!\n";
    swap();
    system("pause");
    return 0;
}

int swap()
{
    int on = 1;
    int off = 0;
    int temp = on;
    on = off; 
    off = temp;
    return 0;
}

enter image description here

Upvotes: 0

Views: 6477

Answers (2)

Frankenstine Joe
Frankenstine Joe

Reputation: 313

Try defining your function on top of main or Just declare on top of main.It now calls swap from .net library

Upvotes: 1

5gon12eder
5gon12eder

Reputation: 25409

Is is because I declare the function after it has been called?

Yes.

By the time the compiler sees the call to swap(), it doesn't know about your function yet. You'd normally get an error along the lines of “call to undeclared function” in this case, were it not for std::swap (which takes two arguments) that you've pulled into your name-space by the using namespace std directive.

In order to fix: Move the definition of swap above main (as a function definition is always also a function declaration) or leave it where it is an put a dedicated declaration

int swap();

above main. I'd also get rid of the using namespace std; as it, as you can see, might do you more harm than good and instead prefix all standard-library types and functions explicitly with std::. But that's not mandatory and also not the root cause of your current issue.

Upvotes: 4

Related Questions