0

Why does the output of this code is 0 10 10.dosnt the variable v without value in both the first and third cases?

#include <iostream>
using namespace std;
void f(bool val)
{
    int v;
    if(val)v=10;
    cout<<v<<endl;

}
int main() {

    f(false);
    f(true);
    f(false);
    return 0;
}
Ridaniel
  • 17
  • 1

4 Answers4

1

Because when val = false this condition if(val) is not satisfied so the uninitialized variable v will be printed out.

At that time the value of v could be 0, the last value, or anything else. It's undefined.

Van Tr
  • 5,889
  • 2
  • 20
  • 44
0

int v just declares the v variable, but doesn't assign a value to it, so its value is undefined, it will be same as the current value in the memory.

you can assign v an initial value when declare, likes int v = 0, so when val is false, the v will be always 0.

Spark.Bao
  • 5,573
  • 2
  • 31
  • 36
0

Your answer could vary as x 10 x where x can be any number. Actually, it's the garbage value. You will get its different value in different compiler on the different platform.

Somewhere you will get 0 10 10 because it buffers the value of v. but somewhere else will get 10 10 10 because it buffers the value at compile time. So, its not correct to say what will be the value of x.

So, you should say the answer will be x 10 x where x is the garbage value.

Rajat Jain
  • 1,339
  • 2
  • 16
  • 29
-3

The answer will be 10 10 10 You need to compare value of val in the if condition statement to get different answers. It is taking the value of v in the if statement because there is no comparison. Try it some other Compilers.

try here https://www.onlinegdb.com/online_c++_compiler