4 ms·
Curly braces designate scope in C like languages: int i = 100; std::cout << i << std::endl; if (1) { int i = 200; std::cout << i <<
by riazrizvi 6y ago
Curly braces designate scope in C like languages:
int i = 100;
std::cout << i << std::endl;
if (1) {
int i = 200;
std::cout << i << std::endl;
}
std::cout << i << std::endl;
giving
100
200
100
They don't seem to serve such a purpose in Pytov. Eyeballing the source, it looks like you'd get this:
i = 100
print (i)
if (True) {
i = 200
print (i)
}
print (i)
giving
100
200
200
So what's the point?
- pansa2 6y ago> it looks like you'd get this Yes, you would - variables in Python have function-scope, not block-scope. It doesn’t look like this project changes anything about Python except trivial bits of syntax.
- zzo38computer 6y agoSo would you in C if you do not redeclare the variable inside of the block. Also in JavaScript (although in JavaScript the type is not declared; in C it is). I don't know how it is working in Python, though.
- deaddodo 6y agoNot sure if you're aware, but you could just write that as: int i = 100; std::cout << i << std::endl; { int i = 200; std::cout << i << std::endl; } std::cout << i << std::endl; And since PyTov is supposed to be C-like, this might be a better example: #include <stdio.h> int main(void) { int i = 100; printf("%i\n", i); { int i = 200; printf("%i\n", i); } printf("%i\n", i); return 0; } Also, the same would occur in C(/C++) if you didn't shadow the variable in the block scope and just called: i = 200
- quietbritishjim 6y ago> Curly braces designate scope in C It's not the curly braces that create the scope as such. It's the block, and the curly braces just happen to create the block. In C++ you can even do this, for example (I was surprised to find it doesn't work in C): int i = 1; if (true) int i = 2; std::cout << i << '\n'; // Prints 1 In any case, the semanics of blocks (whether they create scopes) is totally orthogonal to the syntax of blocks. You can just as easily imagine the reverse: the current colon-indent syntax where blocks do create scopes. Another issue, which other replies have alluded to but not quite spelt out. You'd need to add a syntax to distinguish between regular assignment and declaration. In C you can still choose to assign to the outer-scope variable from a nested scope of you wish, so you don't want i=1 in a nested scope to always declare a new variable that shadows a variable in the outer scope. Oh and one more thing. Your snippet (or equivalent) won't work in all C-style braces languages: in C# it is a compilation error to shadow a variable from an outer scope in the same function (presumably because it's a common source of bugs and extremely easy to just choose a different name for one of the variables).