c – Loops and stuff taken in { … }

Question:

Hello! Such a question worries. There are brackets {} in c++. If in a method, declare a variable in them like this:

void funct(){
int g=0;
  {
     int g=0;
  }
}

then the compiler will not swear. Why? If you explain in assembly language what will happen? Will the function be called with the transfer of all variables available to the top function in {}? if so, how will the variables be passed on the stack? Why would the above construction be acceptable at all? And here's another. Here is the character ";" means the end of the operation, for example int t=a+b; . And what does he do? why can i put it like this:

void f(){
;
} или 
 void f(){ };

and no error? What does the computer do when it encounters a ;? Thank you.

Answer:

{....} is a block of code and can be inserted anywhere a single line can be inserted. You are not confused by the code:

if (....)
   doSmth();

and

if (....) {
   doSmth();
}

But these brackets have one peculiarity – they declare a new scope.

void funct(){
int g=0;
  {
     int g=0; // это другая переменная g, она имеет другой адрес!
     // предыдущая g не доступна по своему имени до закрывающей фигурной скобки.
  }
  // а здесь снова доступна первая переменная.
}

At the assembler level, it looks like this

funct():
    push    rbp
    mov rbp, rsp
    mov DWORD PTR [rbp-8], 0 ; первая g
    mov DWORD PTR [rbp-4], 0 ; вторая g
    pop rbp
    ret

How are variables passed on the stack?

as usual. Although no one bothers the compiler to analyze and do well.

Why would the above construction be acceptable at all?

for example, for lovers of long functions, when you want to add another hundred lines, and the variables (names) are over.

But seriously, such constructions are used all the time – cycles, conditions.

Here is the character ";" means the end of the operation, for example int t=a+b;. And what does he do?

it performs a decorative role for the programmer. It's syntactic sugar. But the compiler can use it if there are a lot of errors in the code, in order to at least somehow separate the operators. Here in Go, you can skip the semicolon, when it is already clear that it should be there.

In the assembly code, it does not appear in any way.

Scroll to Top