So I'm trying to get the user to enter two numbers and get the sum of it as an answer but it gives me the errors error: 'y' was not declared in this scope error: 'x' was not declared in this scope
Here is my work till now:
include <iostream>
using namespace std;
int addNumbers(int x,int y);
int main() {
cout << "enter two nubmers you want to add \n " <<endl;
The compiler is telling you exactly what is wrong. Neither x nor y is declared within main.
1 2 3 4
int main()
{ int x, y;
/* rest of main */
}
PLEASE USE CODE TAGS (the <> formatting button) when posting code. http://v2.cplusplus.com/articles/jEywvCM9/
It makes it easier to read your code and it also makes it easier to respond to your post.
No, that's a poor choice, that proposed solution contains errors, and the use of global variables in this example is just poor design. If global variables are used, why bother passing parameters to the function? And generally speaking the use of global variables is considered bad practice, even if the design issues were resolved.
IF you are an beginer try simple programming first and try not to mess up....so try what i do here
#include<iostream.h>
void main()
{
int a,b,sum ;
cout<<"Enter any two numbers to be added:\n" ;
cin>>a>>b ;
sum=a+b ;
cout<<"\nThe sum of the numbers is:"<<sum ;
}
#include <iostream>
int main() {
int a = 1, b = 1;
std::cin >> a , b; // ==
//cin >> a;
//b;
std::cout << "a: " << a << " b: " << b << std::endl;
a = 1;
b = 1;
std::cin >> ( a , b ); //==
//a;
//cin >> b;
std::cout << "a: " << a << " b: " << b << std::endl;
a = 1;
b = 1;
std::cin >> a >> b; //==
//cin >> a;
//cin >> b;
std::cout << "a: " << a << " b: " << b << std::endl;
return 0;
}
Demo of what using the comma operator like that is really doing.
Also globals are okay to use if they are constants since they can not be modified but if they are not constants you shouldn't make them global since anything can modify them and if you have two programmers working on one program that could cause a lot of problems.
Even global constants can cause problems, especially if its a larger program. What if two people make two global constants called the same thing? It can take a while to work out whats going on, and even longer to fix it.
Global variables aren't bad, they're less favorable ^^; they introduce the "possibility" of variable conflicts - lots of debug time for new folks; or some folks just prefer everything embedded/organized in certain scopes.
And as a beginner, you should practice data integrity - in this case, monitoring and controlling a data's life cycle. A global variables' life cycle may be long, and is hard to monitor; best not to use it unless your scope has maximum priority; it'd be destructive on larger scales.
Anyhow back to OP:
Information on variable declaration:
http://www.cplusplus.com/doc/tutorial/variables/
control + F: Declaration of variables
The tutorial will show the basic ins and outs of variable interaction.