0
#include <stdio.h>

int num1;
void newfun();
void main()
{
    int num2;
    num1 = 10;
    num2 = 20;
    newfun();
    printf("%d %d", num1, num2);
}
void newfun()
{
    int num2 = 30;
    int num1 = 40;
}

The book says that the result of the value is num1=40 and num2=20 but I keep returning back num1=10 and num2=20.

Why the global variable doesn't work?

Thanks

donong
  • 17
  • 6

3 Answers3

0

In the newfun() you declared new variable num1 (same name as global), and local variables have a greater priority than global.

If you want to change global variable num1 you could write:

void newfun()
{
    int num2 = 30;
    num1 = 40;
}
Majkl
  • 153
  • 1
  • 7
0

That shouldn't be the case. 10 and 20 is the correct and expected output. Whenever local and global variables have the same name then the global variable is not accessible inside the function (which has local variable with same name). So basically nothing changes and 10, 20 should be the output.

Sai Sreenivas
  • 1,690
  • 1
  • 7
  • 16
0
int num1 = 40;

int num1 in newfun() is the declaration of a new function-local variable with the same identifier name1 as the global variable. So you don't address the global variable with this statement.

Instead, you initialize the local variable num1 by the value of 40, which is destroyed after the function has been executed since its storage class is automatic.

The global variable still contains the value of 10 as assigned in main() and this is what is printed for it at the call to printf(), which is completely correct.


Side Notes:

  • void main() is not correct. You need to use at least int main() or even better int main (void) to provide a fully prototype.

  • If this is really the exact same example as in the book and it is saying anything else would be the output, you urgently need a better source of knowledge. F.e.: Modern C by Jens Gustedt.

    Others and including this one, you can find in this amazing collection of books regarding C programming:

    The Definitive C Book Guide and List