0
short int PC = 0;

int main() {
    foo(&PC) ;
}

void foo(short int PC) {
    PC++;
}

How do I successfully update the global variable of PC?

Note: PC must be passed as a parameter and the global variable needs to be modified via the parameter.

As you can tell I am new to C and am trying to understand the difference between * and &. Any help would be much appreciated.

2
  • 2
    If your compiler didn't give you a diagnostic message for this code, you'll need to adjust which switches you are using. (it causes undefined behaviour at runtime , at least, due to &PC not having the type short int) Commented Sep 27, 2016 at 4:08
  • I don't see the point in passing a global variable as a parameter. Commented Sep 27, 2016 at 5:52

1 Answer 1

3

You just need to take the argument as a pointer:

short int PC = 0;

void foo(short int *pc) {
    (*pc)++;
}

int main() {
    foo(&PC) ;
}

I moved foo() above main() because in C you have to declare things before they are used. If you prefer you could forward declare it by saying void foo(); at the top and leave the definition below.

Sign up to request clarification or add additional context in comments.

2 Comments

Aha! You also solved my second question too with the (*PC)++;. Without the surrounding parens I was getting the warning that the statement did nothing.
It would probably help if you renamed the argument of foo(). Having two things with the same name (PC) suggests they are the same thing, when they are not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.