March 29, 2024, 08:22:50 AM

News:

Own IWBasic 2.x ? -----> Get your free upgrade to 3.x now.........


Global or local variable

Started by aurelCB, August 27, 2020, 02:20:10 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

aurelCB

August 27, 2020, 02:20:10 PM Last Edit: March 04, 2023, 02:30:59 AM by aurelCB
hello

billhsln

Variables defined within a function are local to that function.  You can use the variable that is defined in the main program any where, but when it is defined in a subroutine, it is local and will not effect the global version, whereas, if it is not defined in the function then it changes the global.

Bill
When all else fails, get a bigger hammer.

Andy

Bill is 100% correct.

To prove it, see attached program and screen shot.

Andy.
Day after day, day after day, we struck nor breath nor motion, as idle as a painted ship upon a painted ocean.

billhsln

A normal compiler would have marked that as a problem.  So, the question becomes, if you change the variable in the subroutine does it stay local or does it update the global one?

Technically the compiler should have given you an error on this.

Bill
When all else fails, get a bigger hammer.

Brian

As far as I am aware, a definition defined inside a SUB is for that SUB only, and is destroyed on leaving the SUB

Brian

jalih

Quote from: aurelCB on August 28, 2020, 03:23:03 AMI agree and i know that very well
but both of you miss my point
look into red variables again:

SUB colorize(w1 , ctl, linenum)
def lineStart, lineLength : int
def i, ctl, linenum, char_start ; int
def p, pLine :int


do you see now ,one time is same variable defined as argument of function and then
is again defined as local...so i am wondering again what is a point in this
if we load some value into argument var-> linenum
then again is terminated by local declaration linenum : int
i am sorry but not make any sense to me !

I see no double declarations. Function argument types are declared at the function body.


jalih

Quote from: aurelCB on August 29, 2020, 11:35:54 AMyes but with same name ..which is not very smart

They are the same! As an old PL/I programmer, I have used to declaring types for procedure arguments at the body:


 test: proc options(main);

  call hello(5);

  hello: proc(n);
    dcl n fixed bin(31);

    dcl i fixed bin(31);

    do i = 1 to n;
      put skip list('Hello World!');
    end;

  end hello;

 end test;

So, hello procedure takes n as parameter but compiler can't know the type of it until it's declared as signed 32 bit integer...