LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   strange output (c) (https://www.linuxquestions.org/questions/programming-9/strange-output-c-502842/)

linuxi 11-18-2006 03:53 PM

strange output (c)
 
Hi,
i have troubles understandig the following code:

Code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

long getNumb()
{
 
  long zahl;
  printf("input number: ");
  scanf("%ld", &zahl);
  return zahl;
}

long getNumbgetNumb()
{
long a, b;
a = getNumb();
b = getNumb();
}   


int main()

    long a,b;
    getNumbgetNumb();
    printf("%ld\n", a);
    printf("%ld\n", b);
      system("PAUSE");   
 
}

For every input in getNumb() i become a=2 b=22 in
main()..y?

p.s. is not a homework :) ..

kaz2100 11-18-2006 03:59 PM

Hi,

both a and b are local.

Happy Penguins.

dmail 11-18-2006 04:04 PM

Take this with a grain of salt as I've been off the mark today.
This should not even compile as getNumbgetNumb doesn't return a value.
a and b in main scope are not initialised and are different variables to those in getNumbgetNumb scope.(edit: which kaz2100 already mentioned)

linuxi 11-19-2006 05:28 AM

Yes i know there are local but why output is 2 and 22? or there is no logical explanation

urzumph 11-19-2006 06:03 AM

You never initialise the a and b declared in main. Thus, their value is never written to, and whatever value is left in that position in ram from whatever program ran before is printed out.

matthewg42 11-19-2006 06:51 AM

Quote:

Originally Posted by linuxi
Yes i know there are local but why output is 2 and 22? or there is no logical explanation

Until you assign a value to a variable, it's value is undefined. The behaviour of a program which is asked to use an undefined variable is also undefined. Read this to mean "It might do something weird. It might do something boring. It might format your hard disk and put sugar in your fuel tank.".

The exact reasons for the value you get will be very deep in how the compiler/links/os is working. It may well be interesting, but it's not, much to do with C the language itself.

linuxi 11-19-2006 10:43 AM

thx for ur explanations :)


All times are GMT -5. The time now is 07:23 PM.