0

When I was resolving merge conflicts, It appeared, that one of the conflict was automatically resolved by git in one of my code piece.

The code that rendered after merge conflict was:

if(condition1)
{
   //Statement 1

}
{
  //Statement 2

}

The code compiled and ran without any error. Is the statement 2 code piece serving as else here? if yes, then what is the use of else keyword?

Karan Desai
  • 3,012
  • 5
  • 32
  • 66
  • 5
    No, the second `{}` is just in it's own scope for no apparent reason. What happens if you remove the braces? – Tim Schmelter Nov 15 '17 at 09:39
  • 1
    That's right. The second pair braces simply define a code block - nothing to do with the first. See also this question: https://stackoverflow.com/questions/6136853/why-does-c-sharp-allow-code-blocks-without-a-preceding-statement – bornfromanegg Nov 15 '17 at 09:45

2 Answers2

1

No the second {} is not a else statement but it just defines a scope ,did you try removing the braces and checking the output again?

1

What you've got is an if statement followed by a block statement. The block statement introduces a new scope. They're two separate constructs.

It's often useful to introduce a block statement if you want to limit the lifetime of an object within your code. For example, you might only want to acquire a lock for a part of a function:

void DoSomething()
{
  // Stuff
  // Stuff
  // Stuff

  {
    Lock lock(mutex);    
  }

  // Stuff
  // Stuff
  // Stuff
}
Sean
  • 60,939
  • 11
  • 97
  • 136