Message Boards Message Boards

0
|
3643 Views
|
3 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Local variable named i in different functions are interdependent

Posted 3 years ago

I write two functions. And use the local variable named i in both functions, the i in function 2 are influenced by the i in function 1. The result of test2 should be 1 to 10, but now it is 12

POSTED BY: tt t
3 Replies

BTW, For is different than Do or Table. Both of those automatically locally scope, AFAIK.

i = -1
test[] := Do[Print[i], {i, 5}]
test[]
i

will print

-1
1
2
3
4
5
-1
POSTED BY: Trevor Cappallo
Posted 3 years ago

Unfortunately, the i in For is not scoped, it is global. The body of For calls test1[] which sets the global i to 12 which terminates the For. If you want different scopes for i.

test1[] := Module[{i}, i = 12]

test2[]
(* Prints 1 to 10 *)

i
(* 11 *)

Or

test1[] := Module[{}, i = 12]
test2[] := Module[{i}, For[i = 1, i <= 10, i++, test1[]; Print[i]]]

test2[]
(* Prints 1 to 10 *)

i
(* 12 *)

Or

i = -1;
test1[] := Module[{i}, i = 12]
test2[] := Module[{i}, For[i = 1, i <= 10, i++, test1[]; Print[i]]]

test2[]
(* Prints 1 to 10 *)

i
(* -1 *)

Suggest you read this.

POSTED BY: Rohit Namjoshi

The first argument of Module (or Block) is a list of variables that you want to "limit the scope to the Module (or Block))" For your example: Define i

i = Green

Define your functions (localizing i in the second is superfluous, because For does it anyway).

test1[] := Module[{i}, i = 12]
test2[] := Module[{i}, For[i = 1, i <= 10, i++, test1[]; Print[i]]]

Try the functions:

test1[]

And this one

test2[]

The value of i is unchanged in the Global scope.

i
POSTED BY: W. Craig Carter
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract