abd_ka's blog

By abd_ka, history, 5 months ago, In English

Are block scopes a good practice in CP ?

What i mean by block scope:

I am not sure if this is the correct naming it, but i will try to explain what i mean by block scope.

A block scope is a scope which isn't created for a function of a loop (for/while), rather a scope which is created by just typing {...} and then code inside it.

int main() { FAST
    int n = 10;
    { // this is a block scope
        int n = 100; 
        cout << n; //this will output "100"
    }
    cout << n; // this will output "10"
}

Why would you ever use this ?

a good example which comes to my mind (which i have used many times before) is when you need to perform two bfs/Dijkstra.

so instead of defining 2 queues, you just define one inside a block scope, and the other inside another block scope. this makes the implementation a bit easier.

what i am asking about

. Does this makes the code slower for any reason ?

. Why doesn't advanced CP'ers use this ?

i am keen to hear what you think.

thank you for reading.

  • Vote: I like it
  • +31
  • Vote: I do not like it

»
5 months ago, # |
  Vote: I like it +6 Vote: I do not like it

Well, I do use block scopes. They come in really handy when compressing an array. But I am not sure if this has any drawbacks.

»
5 months ago, # |
  Vote: I like it -6 Vote: I do not like it

Well, I used to consider it as a kind of UB (using the same name in two variables). So I don't dare to use it before.

»
5 months ago, # |
  Vote: I like it +19 Vote: I do not like it

Well, I usually use it when I have to copy a part of the code into another one, in this way it is annoying to delete all of the declaration parts.

Such as:

{
  int a = 5;
  printf("%d\n",a);
}
{
  // this part is copied from the part above
  int a = 10; // You don't need to delete this 'int'.
  printf("%d\n",a);
}
»
5 months ago, # |
  Vote: I like it +11 Vote: I do not like it

I prefer immediately invoked anonymous functions. It adds the benefit of marking a return value const. Example: 246074577 (precomputing subtree sizes).

»
5 months ago, # |
  Vote: I like it 0 Vote: I do not like it

bro, i use python

»
5 months ago, # |
  Vote: I like it 0 Vote: I do not like it

thanks, if not for this post I would have forgotten about it forever