PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] what will bw the output of this code? c++

 July 20, 2022     c++, function, integer, output     No comments   

Issue

#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

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.



Answered By - Bathsheba
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing