Reputation: 955
I was wondering if the redefinition of a variable in C++ is possible, for example:
void some_function(int some_argument) {
float some_argument=(float) some_argument;
// Do stuff
return some_argument;
}
Is there some way to do this? I know you can change the name, but it's so much cleaner if the name is the same. If not, is there some reason this feature wasn't included?
Thanks in advance.
Upvotes: 1
Views: 9596
Reputation: 11002
The following gives warnings about possible loss of data when converting between int
and float
but it demonstrates how you can pass the variable as one type and work with it in the function as another:
float some_function(int some_argument) {
// Do stuff
return some_argument;
}
int main()
{
float oldval = 3;
float newval = some_function(oldval);
return 0;
}
Upvotes: 0
Reputation: 206577
Is there some way to do this?
You can create a new scope and define a new variable of the same name which shadows the name of the function argument.
void some_function(int some_argument) {
{
float some_argument = 0;
// Do stuff
}
}
However, you cannot use:
void some_function(int some_argument) {
{
float some_argument = (float)some_argument;
// Do stuff
}
}
In the second case, the initialization does not use the function argument to initialize the shadowing variable. It is as bad as
int i = i;
Avoid all these hassles by:
Using different names for the variable and the argument.
void some_function(int some_argument_in) {
float some_argument = (float)some_argument_in;
// Do stuff
}
Using a function overload.
void some_function(float some_argument) {
// Do stuff
}
void some_function(int some_argument) {
some_function((float)some_argument);
}
Upvotes: 2