Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean that "a declaration shadows a parameter"? [closed]

I am trying to make a function that returns double the integer number that I will pass to it. I am getting the following error message with my code:

declaration of 'int x' shadows a parameter int x; "

Here is my code:

#include <iostream>
int doublenumber();
using namespace std;
int doublenumber(int x)// <-- this is the function which returns double the value .
{
    int x;
    return 2 * x;
    cout << endl;
}
int main()
{
    int a;
    cout << "Enter the number that you want to double it : " << endl;
    cin >> a;
    doublenumber(a);

    return 0;
}
like image 994
grandx Avatar asked Aug 31 '15 12:08

grandx


People also ask

What does it mean when declaration shadows parameter?

Declaration Shadows a Parameter Error in C++A variable defined inside an if-else block, function, or a class cannot be used unless and until you have defined it as public . And a public variable, function, or class can be accessed throughout the program.

What is shadow declaration?

Shadowing is a computer programming phenomenon in which a variable declared in one scope (like decision block, method, or inner class) has the same name as another declaration of the enclosing scope. In this case, the declaration shadows the declaration of the enclosing scope.

What is shadowed declaration in C++?

In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope.


2 Answers

You have x as a parameter and then try to declare it also as a local variable, which is what the complaint about "shadowing" refers to.

like image 148
Scott Hunter Avatar answered Nov 15 '22 11:11

Scott Hunter


I did it because your advice was so helpful, and this is the final result :

#include <iostream>
using namespace std;

int doublenumber(int x)
{
    return 2*x;
}

int main()
{
    int a;
    cout << "Enter the number that you want to double it : " << endl;
    cin>>a;
    int n= doublenumber(a);
    cout << "the double value is : " << n << endl;
    return 0;
}
like image 27
grandx Avatar answered Nov 15 '22 10:11

grandx