-1

When I run this cpp code in devC++:

#include <iostream>
using namespace std;

#include <conio.h>

void getdata();
void dis();

void getdata()
{
    int radius;
    cout<<"\n enter radius of circle:-";
    cin>>radius;
}

void dis()
{   
    int rad;
    cout<<"\n num is "<<rad;
}

int main()
{
    //int radius;
    getdata();
    dis();

    getch();
    return 11;
}

My output shows:

enter radius of circle:-15
radius is 15

my question is: radius and rad are local to their functions, then how does rad became the same value as radius? They are in different functions.

Can someone kindly explain what is happening?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Possible duplicate of [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) –  Mar 17 '18 at 05:33
  • @NickyC Err, why that dupe target? – miradulo Mar 17 '18 at 05:35
  • 1
    Possible duplicate of [Why do I see strange values when I print uninitialized variables?](https://stackoverflow.com/questions/4259885/why-do-i-see-strange-values-when-i-print-uninitialized-variables) – miradulo Mar 17 '18 at 05:36
  • Try compiling and running it online, you will get different values –  Mar 17 '18 at 05:42

2 Answers2

-1

Undefined behavior.

When getdata() is called, radius occupies a particular block of memory on the stack, and is populated with the user's input. When getdata() exits, that memory block becomes available for later reuse, and its content is not cleared.

When dis() is then called afterwards, rad is not being initialized, so it picks up whatever random value was already present in the memory block that it occupies.

Most likely, what is happening is that rad happens to occupy the same memory block that radius had previously occupied. That is why you see the same value. But this is not guaranteed, so don't rely on it. Add some additional variables above either radius or rad and you will see different behavior.

Always initialize your variables before you perform operations that are dependent on them.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
-2

If the variable is uninitialized it will hold the garbage value!.

in your caserad will print the garbage value .It may differ every time you compile.