I've encountered an issue with my code, see the following code snippet:
bool flag = false;
if(flag==false)
{
int var=0;
flag=true;
}
if(flag==true)
{
var=10;
}
In this case var is marked as undefined and CCS generates an error, which is perfectly right. As long as a variable is defined inside an if case it's not know to the outside. For sure you can rewrite the code in this case. But in my actual code I've to built an object from a class with a non default constructor and it can't be solved otherwise than with an if case (at least I don't have an idea how)
My actual code:
SelectedSocket2=VCRT_selectset(&MasterSocket,1,-1);
if((SelectedSocket != VCRT_SOCKET_ERROR) && (SelectedSocket != 0))
{
ClientSocket=accept(MasterSocket, NULL, NULL);
CStreamer Streamer(ClientSocket);
CRtspSession RtspSession(ClientSocket,&Streamer);
flag=true;
}
//Streamer, RtspSession are outside unknown and CCS generates an error
Any ideas how I can solve the issue or trick the compiler?
This snippet should work better :
bool flag = false;
int var = 0;
if (flag == false)
{
var = 0;
flag = true;
}
if (flag == true)
{
var = 10;
}
In your code snippet, var
is declared within the if
scope (between its associated {}
). It is destroyed when the first }
is reached. If you want it to stay alive beyond the first if, you have to declare it outside.
EDIT :
With pointer without dynamic allocation (Using char[] to fake allocation) :
// Allocate the needed size for CStreamer (Statically
char _dummyCStreamer[sizeof(CStreamer)];
// Same for CRtspSession
char _dummyCRtspSession[sizeof(CRtspSession)];
SelectedSocket2 = VCRT_selectset(&MasterSocket, 1, -1);
// The following two lines are the trick
CStreamer *streamerPtr = (CStreamer *)_dummyCStreamer;
CRtspSession *RtspSessionPtr = (CRtspSession *)_dummyCRtspSession;
// Go ahead, you can now consider your two pointer as if they were statically allowed
if ((SelectedSocket != VCRT_SOCKET_ERROR) && (SelectedSocket != 0))
{
ClientSocket = accept(MasterSocket, NULL, NULL);
CStreamer Streamer(ClientSocket);
CRtspSession RtspSession(ClientSocket, &Streamer);
streamerPtr->operator=(Streamer);
sessionPtr->operator=(RtspSession);
flag = true;
}
Be careful, streamerPtr
and RtspSessionPtr
have their lifetime bound to _dummyCStreamer
and _dummyCRtspSession
's ones. (Respectively)
Of course, your classes have to implement a proper operator=.