Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what will bw the output of this code? c++

#include <iostream>

using namespace std;


int f(int i){
  int k=0;
  if(i>0)
    {
        int k=i*10;
    }
    else {
        int k= i++;
    }
    cout <<k;
    return i;
}


int main()
{
    cout << f(1);
    cout << ".";
    cout << f(0);

    return 0;
}

This is the code, compiler shows "01.01" which i quite don’t understand, any help will be very much welcomed!

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int k = i * 10; and int k = i++; are declarations of k that shadow the outer k. The statement std::cout << k; in the outer scope therefore always outputs zero.

The only effect of the if body is to increase i by 1. And it only does that if i is zero (or less). That value of i is returned printed.

Thus the output is 01.01. Armed with a line by line debugger, the shadowing effect will be obvious.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading