英文:
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 关键字。请注意它不会在每个柱状图上重置。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论