Below is a code which I am not understand.
#include<stdio.h>
int main(int argc, char *argv[])
{
int num;
printf("\n Number: " );
scanf("%d", &num);
if (num >= 0)
{
int abs = num;
}
else
{
int abs = -num;
}
{
int abs;
printf("\n Values are %d %d", num ,abs);
}
return 0;
}
When I enter a number as 4, the output is Values are 4 4
When I enter a number as -4, the output is Values are -4 4
I am not able to understand how is it able to print the absolute value?. the variable abs defined in the if loop and else loop should have been deallocated after exiting.
Kindly let me know.
Regards,
darkie
Hilarious code.
It relies on the fact that all three definitions of abs will be allocated on the same place on the stack, due to compiler optimization.
The third abs has to be random garbag, the garbage turns out to be the result of the previous variable with the same name (the name would not matter).