Блог пользователя abd_ka

Автор abd_ka, история, 5 месяцев назад, По-английски

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.

  • Проголосовать: нравится
  • +31
  • Проголосовать: не нравится

»
5 месяцев назад, # |
  Проголосовать: нравится +6 Проголосовать: не нравится

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 месяцев назад, # |
  Проголосовать: нравится -6 Проголосовать: не нравится

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 месяцев назад, # |
  Проголосовать: нравится +19 Проголосовать: не нравится

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 месяцев назад, # |
  Проголосовать: нравится +11 Проголосовать: не нравится

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

»
5 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

bro, i use python

»
5 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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