Is it better to declare a variable inside or outside a loop?

Performance-wise, let’s try concrete examples: public void Method1() { foreach(int i in Enumerable.Range(0, 10)) { int x = i * i; StringBuilder sb = new StringBuilder(); sb.Append(x); Console.WriteLine(sb); } } public void Method2() { int x; StringBuilder sb; foreach(int i in Enumerable.Range(0, 10)) { x = i * i; sb = new StringBuilder(); sb.Append(x); Console.WriteLine(sb); … Read more

C++ – value of uninitialized vector

The zero initialization is specified in the standard as default zero initialization/value initialization for builtin types, primarily to support just this type of case in template use. Note that this behavior is different from a local variable such as int x; which leaves the value uninitialized (as in the C language that behavior is inherited … Read more

Can I declare variables of different types in the initialization of a for loop? [duplicate]

Yes, that is prohibited. Just as otherwise you cannot declare variables of differing types in one declaration statement (edit: modulo the declarator modifiers that @MrLister mentions). You can declare structs for (struct { int a = 0; short b = 0; } d; d.a < 10; ++d.a, ++d.b ) {} C++03 code: for (struct { … Read more