开发者

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.


Delete the x = 7 line, move the print statement before you print the value or set a different variable to 7 (i.e. write y = 7 instead of 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 :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜