Here is the code:

#include <cstdlib>
#include <iostream>

using namespace std;

//Declare function
int triangle(int num);

int main() {
    int n;
    cout<<"Enter a number and press RETURN: ";
    cin>> n;
    cout<<"Function returned:"<<triangle(n)<<endl;
    return 0;
}

//define function
int triangle(int n){
    int i;
    int sum=0;
    for(i=1; i<=n; i++)
        sum=sum+i;
    return sum;
}

What my question is, why does this work if it's declared as

triangle(int num)

but defined as

triangle(int n)

I thought they had to be the same? When I put this in one compiler it works and in another I get an error? Can someone explain this to me please?

Because the compiler see's it as :

int triangle(int);

Yep, this is also why to save your self time you can declare a function above main with int func1(int,char,string); and then below main define it as int func1(int beez, char doodz, string awesomeIHATESTDNAMESPACE){return 0;}

Declaring without argument names saves time and money.

The top part is declared as function prototype, so compiler knows that you have the function's definition afterward and keep the information for use later. Only the prototype can be declare without variable name, but it would be more clear if both have the exactly the same declaration (easier to figure out for those who are not familiar).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.