Can you explain why variables have different values when they are declared inside a function?

王林
Release: 2024-02-12 17:30:06
forward
330 people have browsed it

Can you explain why variables have different values ​​when they are declared inside a function?

Question content

This is the first time I write code. But the value of variableleftis always-1.

func diameterofbinarytree(root *treenode) int { var longest int var left int var right int max := func(a, b int) int { if a > b { return a } return b } var dfs func(*treenode) int dfs = func(node *treenode) int { if node == nil { return -1 } left = dfs(node.left) right = dfs(node.right) longest = max(longest, left+right+2) return (max(left, right) + 1) } dfs(root) return longest }
Copy after login

After changing the code like this, the left side has the value on the right side.

func diameterOfBinaryTree(root *TreeNode) int { var longest int max := func(a, b int) int { if a > b { return a } return b } var dfs func(*TreeNode) int dfs = func(node *TreeNode) int { if node == nil { return -1 } left := dfs(node.Left) right := dfs(node.Right) longest = max(longest, left+right+2) return (max(left, right) + 1) } dfs(root) return longest }
Copy after login

What's the difference? ? please tell me.

I thought the variableleftshould have a different value after the recursion, but it doesn't.

Solution

In the first case, theleftvariable is inside the closure of the inner lambda. This means that the variable is "global" from the function's perspective. Since the lambda is recursive, each call destroys the previous value, which at the end (of the recursion) has a value of -1 (the recursive base case) and never changes thereafter (when returning from the recursion).

In the second case,leftis a local variable, which is then pushed or popped onto the stack on each call.

The above is the detailed content of Can you explain why variables have different values when they are declared inside a function?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!