Where do you put the type in Chapel variable declarations?
More specifically, what’s the difference between var a = 42: int; and var a: int = 42;?
Where do you put the type in Chapel variable declarations?
More specifically, what’s the difference between var a = 42: int; and var a: int = 42;?
Three basic background facts for this question:
Chapel's variable declaration syntax is: var ident: type = init;
Chapel supports compile-time type inference
In Chapel,
:serves two roles:Given that, the declaration:
says "declare a variable named
a, whose type isintand whose initial value is 42." Whereas,says "declare a variable named
a, whose type (since it's not specified) will be inferred from its initializer, which is the value 42 cast to anint."Now, in Chapel,
42is interpreted as anintby default, so this final declaration is really no different than:and all three of the declarations above have the same net effect.
Things get slightly more interesting when you mix different types. For example:
says that
bshould be an 8-bit integer whose initial value is 42. In Chapel, even though the inferred type of 42 isint(which is a 64-bit int), since it is a literal value that can be represented in fewer than 8 bits, the compiler will automatically downcast it to fit into an int(8).Or, the downcast could be made explicit, using the following form:
But consider:
this will be an error because
ais a default int variable (64 bits) and Chapel doesn't support implicit downcasts from variables of wider int representations to narrower ones. So in this case, you'd need to write this declaration as one of the two forms:Needless to say, since this second form is a bit pedantic, we tend to prefer the former of the two.