简体   繁体   中英

how do i print output as 5 of the following program?

# include <stdio.h>

int x = 5;
int main(void)
{

        int x = 7;
        printf("output = %d\n", x);

}

The above program shows output as 7 . How to print 5 in c ?

thanx...

So you're asking how to access a global that's shadowed by a local? You can't in that scope, but something like this should work

# include <stdio.h>

int x = 5;
int get_global_x()
{
  return x;
}

int main(void)
{

        int x = 7;
        printf("output = %d\n", get_global_x());

}

Don't redeclare the x variable in the main function...

In fact, i'm sensing (perhaprs wrongly) that there's another question behind your code, but i'll keep my reaction to it short: if you want to mix global variables and local variables, try to have a convention to distinguish them; for example globals in ALL_CAPS to shout out its scope :)


EDIT: By the way, you should be getting at least a warning from your compiler for redefining a different scope/same name variable. it's really not recommended doing that. Try to always aim for minimum warnings...

You need to give your two variables meaningful names. I'm sure you aren't using x in your real code so do the two vars actually have the same meaning and therefore the same name? If so you could at least do (assuming your ints are counts, but works for all other purposes):

int global_countOfThings = 5;
int main(void)
{
    int countOfThings  = 7;
    printf("output = %d\n", global_countOfThings );    
}

But hopefully you'll be able to do something like:

int countOfDucks = 5;
int main(void)
{
    int countOfGeese  = 7;
    printf("output = %d\n", countOfDucks );    
}

And of course if you can some how change your code to not use globals you'll be better off in the long run.

You are declaring the same variable in global and local scope. If the same variable is declared in global and local scope, the variable will be treated as local variable. That's the reason you are getting the answer as 7.

删除x = 7行,在打印值之前移动print语句,或将其他变量设置为7(即,写y = 7而不是x = 7)。

u have already declared x to behave as if it is a global variable.to print 5 u can write the pritf statement as: printf("%d\\n",x-2); The above would print 5.

If you want it 5, why you assign 7? :-) Or you want to access global variable with the same name as local one? Then you might use namespaces... Not sure about C :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM