我有一个烦人的错误,我忘记写do一个do ... while循环。
int main() {
int status=1;
/*do*/ {
status = foo();
} while (status);
}
Run Code Online (Sandbox Code Playgroud)
为什么这仍然编译和运行?在我看来,编译器应该拒绝这是荒谬的或至少发出警告(-Wall我的编译器选项中有)。我正在使用 C++11。
据我所知,大括号代码运行{ ... },然后程序检查 while 子句中的条件。
我有时会使用大括号来隔离代码块,以避免以后错误地使用变量.例如,当我SqlCommand在同一个方法中放入几个s时,我经常复制粘贴代码块,最后混合名称并执行两次命令.添加大括号有助于避免这种情况,因为SqlCommand在错误的位置使用错误将导致错误.这是一个例子:
Collection<string> existingCategories = new Collection<string>();
// Here a beginning of a block
{
SqlCommand getCategories = new SqlCommand("select Title from Movie.Category where SourceId = @sourceId", sqlConnection, sqlTransaction);
getCategories.Parameters.AddWithValue("@sourceId", sourceId);
using (SqlDataReader categoriesReader = getCategories.ExecuteReader(System.Data.CommandBehavior.SingleResult))
{
while (categoriesReader.Read())
{
existingCategories.Add(categoriesReader["Title"].ToString());
}
}
}
if (!existingCategories.Contains(newCategory))
{
SqlCommand addCategory = new SqlCommand("insert into Movie.Category (SourceId, Title) values (@sourceId, @title)", sqlConnection, sqlTransaction);
// Now try to make a mistake and write/copy-paste getCategories instead of addCategory. It will not …Run Code Online (Sandbox Code Playgroud) 在C#中,您可以在未附加到任何其他语句的方法中创建块.
public void TestMethod()
{
{
string x = "test";
string y = x;
{
int z = 42;
int zz = z;
}
}
}
Run Code Online (Sandbox Code Playgroud)
此代码编译并运行,就像主方法中的大括号不存在一样.还要注意块内部的块.
有没有这种情况有价值?我还没有找到,但我很想知道其他人的发现.
我遇到了一个项目,在那里我发现了一些我无法理解的代码.我刚开始C++,所以对我来说这似乎是个大问题.我提供的项目很少,我无法理解.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题......
do-while循环的内部括号中发生了什么?do-while循环内初始化变量(我提到过)的范围是什么
?帮我理解这个.
我试图理解下面的代码 - 下面匿名块的用途是什么
{
Console.WriteLine("Hello World2");
}
Run Code Online (Sandbox Code Playgroud)
上面的代码在一个方法中可用 - 我是 C# 的新手并试图理解它。
这是好习惯吗?或者我应该只是更换之间的代码块{,并}用功能?它可以重复使用(我承认),但我这样做的唯一动机是解除分配,colsum因为它是巨大的而不是必需的,这样我就可以释放分配的内存.
vector<double> C;
{
vector<double> colsum;
A.col_sum(colsum);
C = At*colsum;
}
doSomething(C);
Run Code Online (Sandbox Code Playgroud) 以下面的C#函数为例:
static void Main(string[] args)
{
var r = new Random();
{
var i = r.Next(); ;
Console.WriteLine("i = {0}", i);
}
var action = new Action(delegate()
{
var i = r.Next();
Console.WriteLine("Delegate: i = {0}", i);
});
action();
}
Run Code Online (Sandbox Code Playgroud)
以下块仅作为C#语法糖存在,以在源代码中强制执行额外的变量范围层,如本SO问题中所述.
{
var i = r.Next(); ;
Console.WriteLine("i = {0}", i);
}
Run Code Online (Sandbox Code Playgroud)
我通过使用ILSpy反编译生成的程序集来证明这一点,并得到:
private static void Main(string[] args)
{
Random r = new Random();
int i = r.Next();
Console.WriteLine("i = {0}", i);
Action action = delegate
{
int …Run Code Online (Sandbox Code Playgroud)