4

I came across one project,where I found some code which I is not understandable to me. I just started with C++, so it seems like a big problem for me. I am providing few lines of my project,which I am not able to understand.

class abc
{
     public:
       //some stuff
       abc();
};

abc::abc()
{
    int someflag = 0;
    //code
    if(someflag == 0)
    {
         do
         {
             //few strcpy operations
             {                 //(My Question)Without any condition braces started
                   //variable initialization
             }
         }while(condition);
    }
}

Now my questions...

  1. What we can achieve by doing this operation?
  2. What is happening in inside braces of do-while loop?
  3. What is the scope of the initialized variables (I mentioned) inside do-while loop?
  4. Is it C++11?

Help me to understand this.

4

4 回答 4

7
  • What we can achieve by doing this operation?

You introduce a scope block for the variables inside.

  • What is happening in inside braces of do-while loop?

See above.

  • What is the scope of the initialized variables (I mentioned) inside do-while loop?

The variables go out of scope at the end of the braces, they're there for that sole reason. One use case I can think of for this is a scoped_lock or something similar to it for multi-threaded applications.

  • Is it C++11?

No.

于 2013-08-07T05:20:37.873 回答
2

即使在 C 语言中,您也可以在允许语句的任何位置打开大括号。

这允许在不干扰封闭范围的情况下声明和使用新变量。例如:

... code before ...
{
    int i = 0, sum = 0;
    while (i < n) {
        sum += dothis(data[i++]);
    }
    dothat(sum);
}
... code after ...

这两个变量isum封闭范围内的同名变量无关:这两个变量在进入块时创建,在退出块时销毁(而ndata外部定义)。这可以通过避免声明和使用之间或声明和初始化之间的分离来提高可读性(在旧 C 中,您不允许在使用之前放置变量声明......所有局部变量都必须在函数开始时声明:一个烦人的问题如果你还不知道给他们的价值)。

如果您在 C++ 中并且这些块局部变量具有类类型,则在进入块时(而不是在进入函数时)调用构造函数,并在退出块时立即销毁。这对于例如锁非常有用

 {
     Lock mylock(resource);
     use_resource();
 }
于 2013-08-07T05:42:39.227 回答
1

以下是您的答案:

答案 1,2。这用于定义新的范围。

Ans 3.一旦控件移出块,变量的范围就结束了

Ans 4.可能编码器来自C背景,并且不像C中那样特定于C ++ 11,变量只能在新范围的开头声明。

请查看THISTHIS以供进一步参考。

于 2013-08-07T05:17:05.567 回答
0

C++中有五种作用域

Function
File
Block
Function Prototype
Class

您共享的代码显示“块范围”

块范围

块是包含在花括号 ( {....} ) 中的 C++ 代码部分。在块中声明的标识符具有块范围,并且从它们的定义点到最里面的包含块的末尾都是可见的。块中的重复标识符名称隐藏了在块外部定义的具有相同名称的标识符的值。在块中声明的变量名是该块的本地变量。它只能在它和它下面包含的其他块中使用。

于 2013-08-07T05:26:24.417 回答