davzter
davzter

Reputation: 1

Why does one variable get the same value as another value

So the function "thinkOfANumber" gives the variable "x" the value 108. Then, we go in to the function "mindReading" that has the variable "secrets" which isn't given any value. But somehow it get the same value as "x". My guess is that it has something to do with the stack and memory. Could someone explain it for me?

The code:

void thinkOfANumber(){
    int x = 108;
    printf( "This function thinks of a secret number (%d)\n", x);
}

void mindReading(){
    int secret;
    printf( "This function believes that the other functions secret is: %d!\n", secret); //Prints 108
}

void main(){
    thinkOfANumber();
    mindReading();
    return 0;
}

Upvotes: 0

Views: 262

Answers (3)

Hasibul Islam Polok
Hasibul Islam Polok

Reputation: 105

C/C++ local variables are given memory when it is needed. Here the secret variable doesn't have any memory assigned. So it is actually following the address of x here. Look at this code here,

#include<stdio.h>

void a(){
    int x = 40;
    int y=30;
    printf( "This function thinks of a secret number (%d)\n", x);
}

void b(){
    int xx;
    int z;
    printf( "This function believes that the other functions secret is: %d !\n", xx);
    printf("%d\n",z);
}

int main(){
    a();
    b();
    return 0;
}

Here the secret is getting value of x and z is getting value of y. If you change the value of secret in the function b then this will assign a new memory for the variable secret.

Upvotes: 0

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

Your variable isn't initialised and will give undefined behaviour. This may include but not limited to -

  • Your program produces different results every time it is run.

  • Your program consistently produces the same result.

  • Your program works on some compilers but not others.


In your case, the uninitialised variable is probably pointing to the memory location storing the address of the initialised variable x. But atleast according to me, this wouldn't be the case everytime and would run in an undefined manner on different compilers or different machines.

Remember to Always initialise your variables

Upvotes: 2

cigien
cigien

Reputation: 60208

Reading from a default initialized int is undefined behavior, since it has an indeterminate value.

When reading from secret, the compiler might be reading the value from a register that just happened to be holding the value of x.

In any case, this is not behavior that you can rely upon, even on the same machine, with the same compiler, with the same compilation flags, etc.

Upvotes: 5

Related Questions