Simple C++ program to add two integers I started learning C++ and the first exercise was to create a small program to add two numbers. No more requirements. I did this and put a small validate the user input. I am sure that it could be much better written, so I appreciate all the critics and suggestions.

#include &lt;iostream&gt;

int x;
int sum = 0;
int i = 0;

int addTwoNumbers()
{
    while(i&lt;2)
    {
        std::cin &gt;&gt; x;
        if(std::cin.fail())
        {
           std::cout &lt;&lt; "Error! Invalid Input" &lt;&lt; std::endl;
           std::cin.clear();
           std::cin.ignore(256,'\n');
        }
        else
        {
             sum += x;
             i++;
        }
    }
    return sum;
}
int main()
{
    std::cout &lt;&lt; "Enter two integers" &lt;&lt; std::endl;
    return sum = addTwoNumbers();
}
Good job on your first program!

Before moving on to the review, a quick note on using namespace std

As long as you do it in a cpp file (and not a header), bringing in symbols from a namespace one at a time is absolutely fine, since you are in control:

#include &lt;iostream&gt;

using std::cout;
using std::cin;
using std::endl;


Errors

main's return value

The main()'s return value is for program status, not program output. I suspect you meant to do:

cout &lt;&lt; "the sum is: " &lt;&lt; addTwoNumbers() &lt;&lt; endl;
return 0;


Good practice improvements

Avoid globals

int x;
int sum = 0;
int i = 0;


These have no business being global variables, they belong inside of your functions, as close to their first use as possible:

for(int i=0; i&lt;2;)
{
    int x;
    cin &gt;&gt; x;


istream::fail() vs operator bool()

Edit Disregard this recommendation. See the comment below.

instead of if(std::cin.fail()) you should simply do if(std::cin), it actually covers more scenarios as well.

istream::ignore()

Whenever you use an arbitrary number like 256, it's a sign that something is not how it should be. In this specific case, you want to do cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n')

From a higher level:

addTwoNumbers() does too many things

Try to keep your functions short, single-purpose and reusable.

As guidance, look at this version of your main().

int main() {
  cout &lt;&lt; "Enter two integers" &lt;&lt; endl;

  int first = getNumber();
  int second = getNumber();

  cout &lt;&lt; "the sum is: " &lt;&lt; (first + second) &lt;&lt; endl;

  return 0;
}


getNumber() would now be be a usefull and reusable piece of code, which is what functions should be.