Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between constant variable which is type of list and constant list

Tags:

flutter

dart

This is a basic question, but can't find elsewhere.

In dart we can declare a constant variable as

const foo = [1,2,3];

or

var foo = const [1,2,3];

Is there any performance related change if we use either any one.

like image 641
balu k Avatar asked Nov 22 '25 19:11

balu k


2 Answers

When you do

const foo = [1, 2, 3];

It means foo will always be equal to [1, 2, 3] independently of the previously executed code and won't change its value later.


When you do

var foo = const [1, 2, 3];

It means that you are declaring a variable foo (and not a constant) which equals at this moment to the constant [1, 2, 3] (it is not dependant on the previously executed code). But the value foo can change and you could do later:

foo = const [1, 2];

which will be legit since foo is a variable. You couldn't do that with foo as a constant (since it is constant)


Therefore, it is better when you can to write

const foo = [1, 2, 3];

because it indicates to the compiler that foo will never change its value.

like image 80
Valentin Vignal Avatar answered Nov 24 '25 23:11

Valentin Vignal


If constants are called literals and literals are data represented directly in the code, how can constants be considered as literals? The article from which you drew the quote is defining the word "constant" to be a synonym of "literal". The latter is the C++ standard's term for what it is describing. The former is what the C standard uses for the same concept.

I mean variables preceded with the const keyword are constants, but they are not literals, so how can you say that constants are literals?

And there you are providing an alternative definition for the term "constant", which, you are right, is inconsistent with the other. That's all. TP is using a different definition of the term than the one you are used to.

In truth, although the noun usage of "constant" appears in a couple of places in the C++ standard outside the defined term "null pointer constant", apparently with the meaning you propose here, I do not find an actual definition of that term, and especially not one matching yours. In truth, your definition is less plausible than TutorialPoint's, because an expression having const-qualified type can nevertheless designate an object that is modifiable (via a different expression).

like image 42
Janvi Patel Avatar answered Nov 24 '25 21:11

Janvi Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!