Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will statements after "return" keyword be executed?

I'm C++ beginner, would like to know the impact of this scenario:

PCONSOLE_SCREEN_BUFFER_INFOEX GetConsoleInfo(void) {
    WaitForSingleObject(m_hSync);   // m_hSync is HANDLE to mutex created using CreateMutex()

    return m_pcsbi;    // m_pcsbi is of type PCONSOLE_SCREEN_BUFFER_INFOEX

    ReleaseMutex(m_hSync);      // <== will this line be executed?
}

Wonder will the [ReleaseMutex()] be executed?

like image 685
tongko Avatar asked Jan 23 '26 02:01

tongko


2 Answers

There's no way to get to that code in your case. If you have a conditional return (e.g. if (ptr==nullptr) return; ) then there are of course conditions in which the return will be skipped. But an unconditional return will be the last of the statements executed.

However, RAII style cleanup does happen after return.

like image 82
MSalters Avatar answered Jan 25 '26 16:01

MSalters


No, after a return statement, the destructors of the scope Objects will be called and the program will exit the function.

int main() { //Step 1
   GetConsoleInfo(); //2

   return (0); //6
}

PCONSOLE_SCREEN_BUFFER_INFOEX GetConsoleInfo(void) { //3
    WaitForSingleObject(m_hSync); //4

    return m_pcsbi; //5

    ReleaseMutex(m_hSync);
}

Maybe you should do something like :

int main() {
   WaitForSingleObject(m_hSync);
   GetConsoleInfo();
   ReleaseMutex(m_hSync);
   return (0);
}

PCONSOLE_SCREEN_BUFFER_INFOEX GetConsoleInfo(void) {
    return m_pcsbi;
}
like image 37
Elfayer Avatar answered Jan 25 '26 16:01

Elfayer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!