Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Stack Variables

Tags:

c++

Given the following function, will each of the local variables be declared on the stack?

std::string reallyCoolFunction(unsigned int a)
{
   if( a < 20 ) 
   {
     std::string result1 = "This function is really cool";
     return result1;
   }

   if( a >=20 && a <= 40 )
   {
     std::string result2 = "This function is kind of cool";
     return result2;
   }

   if( a > 40 )
   {
     std::string result3 = "This function is moderately cool";
     return result3;
   }

 std::string result4 = "This function really isn't that cool"; 
 return result4; // remove warning

}

In this situation, only one std::string is actually required, do all 4 get allocated on the stack, or does only 1 get allocated?

like image 503
lcs Avatar asked Jan 22 '13 15:01

lcs


People also ask

What is a condition variable in C++?

A condition variable is an object able to block the calling thread until notified to resume. It uses a unique_lock (over a mutex) to lock the thread when one of its wait functions is called. The thread remains blocked until woken up by another thread that calls a notification function on the same condition_variable object.

What does it mean to conditionally condition on an event?

Conditioning on an event (such as a particular specification of a random variable) means that this event is treated as being known to have occurred. This still allows us to specify conditioning on an event {Y = y} where the actual value y is an algebraic variable that falls within some range.

What's under the hood of a conditional variable?

Let's reveal what's under the hood. Conditional variable is essentially a wait-queue, that supports blocking-wait and wakeup operations, i.e. you can put a thread into the wait-queue and set its state to BLOCK, and get a thread out from it and set its state to READY.

How do you understand conditioning on a random variable?

To understand conditioning on a random variable, we need the more general idea of conditioning on information. A probability measure by itself gives us prior probabilities for all possible events. But probabilities that certain events happen change if we know that certain other events do or do not happen.


1 Answers

The decision is up to the compiler: since the automatic variables go out of scope before the next one comes in scope, the compiler can re-use their memory. Keep in mind that "stack" variables are actually variables with automatic storage duration according to the C++ specification, so they may not be on the stack at all.

like image 177
Sergey Kalinichenko Avatar answered Oct 02 '22 04:10

Sergey Kalinichenko