Re: variables in c

  • From: "Marlon Brandão de Sousa" <splyt.lists@xxxxxxxxx>
  • To: programmingblind@xxxxxxxxxxxxx
  • Date: Sat, 22 Sep 2007 08:02:42 -0300

You can have globals and local variables with the same name. How the
compiler will handle this is another question that can not be
explained quikcly, but this is a specification of the language so you
can use it.
It turns obvious that using same name variables is a stupid idea, so
folks ave worked on name conventions to make code more easily
readable.
You are right when you stated that line 2 declares two global
variables, called x and y. Your function also declares a x and y
variables, but this are accessible only inside your function.
Everytime your function is called two variables are created in the
stake and are referensed by the names x and y, and when your function
ends these variables are cleaned from the stake, they are destroied.
C++ does provide a scope operator which will allow you to modify
variables with the same name of the ones in your function, but the
best advise is to use unic name  to global variables so your code is
clearer.
Global variables are cause of some controverses ... in genneral try to
use them only when you really need them.
hth
Marlon

2007/9/22, Daniel Dalton <daniel.dalton47@xxxxxxxxx>:
> Hi,
>
> If I write:
>
> #include <stdio.h>
> int x =6, y =78;
> void my_function(void);
> int main ()
> {
> printf("\nx =%d and y =%d", x, y);
> my_function ();
> printf("Left my_function\n");
> printf("\nx now =%d and y now =%d", x, y);
> }
>
> void my_function (void)
> {
> int x =124, y =245;
> printf("\nIn my_function\n");
> printf("x =%d y =%d\n", x, y);
> }
>
> So are both x and y variables local?
>       
> The second line of the program(int x, y;) isn't in a function. So how
> does the compiler know what function they are for? Are they global
> variables? If they are then how can you have a local variable called the
> same thing as a global variable?
> Thanks,
>
> -- Daniel Dalton
>
> http://members.iinet.net.au/~ddalton/
> daniel.dalton47@xxxxxxxxx
> __________
> View the list's information and change your settings at
> //www.freelists.org/list/programmingblind
>
>


-- 
When you say "I wrote a program that crashed Windows," people just
stare at you blankly and say "Hey, I got those with the system, for
free."
Linus Torvalds
__________
View the list's information and change your settings at 
//www.freelists.org/list/programmingblind

Other related posts: