Welcome to the world of C++ coding! Looks like there's more than a few issues in the code here - let's break it down and see what we can find.
First and foremost, to answer your original question, your declaration of x (in function1
) was made outside of the function you tried to use the variable in (in main
). C++ can't normally see variables you declare in one function when it's running in another; that's by design, and is called scope.
To start, the code won't compile for a number of reasons, first and foremost the presence of stray backticks in your code at the very end. These need to be removed.
int main ()
{
function1( x);
return 0;
}` ` //<-- the ` ` will make the compiler angry
Now let's have a look at what's causing the error: x isn't yet declared. In C++, a variable has to be "declared" before it can be used. Since "x" hasn't been declared before its use in function( x);
, the compiler kicks it back since it doesn't know what "x" means. Try this:
int x = 0;
function1( x);
We're not quite done yet, though. Once we make this change, the compiler will throw another error: In function 'int function1(int)': 8:5: error: declaration of 'int x' shadows a parameter
. You've already included an int x in the definition of function1; by creating another int x
inside function1, you've steamrolled your original x
. Let's change that from a definition to an assignment.
function1(int x)
{
x =1;
cout << x << endl;
return 0;
}
Getting clsoer, but we've got one more error: 6:16: error: ISO C++ forbids declaration of 'function1' with no type [-fpermissive]
. THis is telling you function1
needs to have a return type, which is a keyword in front of the function's name that tells the compiler what type of data it returns (void
if it doesn't return any). Looks like you're using return 0;
- why not return an int?
int function1(int x)
Now, at last, we've got code that compiles and runs.
#include<iostream>
using namespace std;
int function1(int x)
{
x =1;
cout << x << endl;
return 0;
}
int main ()
{
int x = 0;
function1( x);
return 0;
}
Try it here!
Good luck!