what is the difference between using var and not using it when declaring variable?

huangapple go评论58阅读模式
英文:

what is the difference between using var and not using it when declaring variable?

问题

I can declare a variable without using var

我可以声明一个变量而不使用 var

int test_var = 5

整数 test_var = 5

I can also declare using var keyword.

我也可以使用 var 关键字来声明。

var int test_var = 5

var 整数 test_var = 5

What is the difference between the 2 different methods? If there is no difference, then why have var in the first place?

这两种不同方法之间有什么区别?如果没有区别,那么为什么一开始要使用 var

I am using pinescript v5.

我正在使用 Pinescript v5。

英文:

I can declare a variable without using var

int test_var = 5

I can also declare using var keyword.

var int test_var = 5

What is the difference between the 2 different methods? If there is no difference, then why have var in the first place?

I am using pinescript v5.

答案1

得分: 1

当使用 var 关键字时,变量仅在首次初始化,如果声明在全局范围内则是在第一个柱状图上,如果声明在本地块内则是在第一次执行本地块时。之后,在后续的柱状图上,它将保留其上一个值,直到我们为其重新分配一个新值。

如果您不使用 Var 关键字,该值将在每个新柱状图上重置。

您可以在此处阅读更多信息

以下代码示例显示了一个没有使用 Var 关键字的变量,注意其值始终为1或-1,因为它在每个柱状图上都会被重置为0。第二张图片是相同的代码,但使用了 Var 关键字。请注意它不会在每个柱状图上重置。

what is the difference between using var and not using it when declaring variable?

使用 Var 关键字的相同代码
what is the difference between using var and not using it when declaring variable?

英文:

When the var keyword is used, the variable is only initilized once, on the first bar if the declaration is in the global scope, or the first time the local block is executed if the declaration is inside a local block. After that, it will preserve its last value on successive bars, until we reassign a new value to it.

If you don't use the Var keyword the value will be reset on each new bar.

You can read more about it here

Below code example shows a variable without Var keyword, notice the value is always either 1 or - 1 since it gets reset to 0 every bar. The second picture is the same code but with the Var keyword. Notice it doesn't reset every bar

what is the difference between using var and not using it when declaring variable?

Same code using Var keyword
what is the difference between using var and not using it when declaring variable?

huangapple
  • 本文由 发表于 2023年5月18日 10:50:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277409.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定