0

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?

4
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by Taywin
0

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.

Edited by argio: n/a

0

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).

Edited by Taywin: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.