V
V
Vladimir Mironov2015-11-07 21:50:08
Programming
Vladimir Mironov, 2015-11-07 21:50:08

What is good manners in c++?

I watch a video on C++ and the author explains how the functions work and writes the following code for clarity:

#include <iostream>
using namespace std;
int sum(int,int);
int main()
{
  int num1;
  int num2;
  cout << "Введите первое число: ";
  cin >> num1;
  cout << "Введите второе число: ";
  cin >> num2;
  cout << sum(num1,num2) << endl;
  return 0;
}
int sum(int number1, int number2)
{
  return number1 + number2;
}

But the second option will also work:
#include <iostream>
using namespace std;
int sum(int number1, int number2)
{
  return number1 + number2;
}
int main()
{
  int num1;
  int num2;
  cout << "Введите первое число: ";
  cin >> num1;
  cout << "Введите второе число: ";
  cin >> num2;
  cout << sum(num1,num2) << endl;
  return 0;
}

So the question is - is it a good idea to create a function in advance, and then describe it (as in the first option) or is it possible to immediately describe the function (as in the second)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Vushnyakov, 2015-11-07
@Siseod

What exactly is a prototype for? Why can't we limit ourselves to using a single function declaration? The prototype became necessary after the C language standards changed in such a way that before calling a function in a file, it must be declared in some way. The problem is that a function name has a global scope (if its description is outside any local scopes). Let's assume that the description of the function is in a separate source file. Let's also assume that we want to call the same function in several other source files. If there is no prototype, then a full description of the function must be included in each such source file. The compiler will interpret this as an override. If we use a prototype, then we can include this prototype in as many source files as we need.
Taken Here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question