Simultaneous execution of both if and else blocks - c++

In C or C++
if ( x )
statement1;
else
statement2;
For what value of x will both statements be executed?
I know we can execute if-else together like this:
if(1){
goto ELSE;
}
else{
ELSE:
}
Is there any way, like a value?
(Which I think is not possible. Asking because someone is arguing!)

for what value of x both statements will be executed??
Only in this case (on unix-like systems):
pid_t pid;
pid = fork();
if (pid == 0){
//some code
}
else {
//some code
}
In this case both branches will be always called simultaineously (well, more or less simultaneously), but in different processes.
I know we can execute if-else together like this:
This:
if(1){
goto ELSE;
}
else{
ELSE:
}
is a wrong construct. You need to use something like this instead:
if ( condition) {
//some code here
...
}
... //some other code here
If one branch is always called, then you don't need "else".

for what value of x both statements will be executed?
There is no such value: either the value evaluates to true (something != 0), or it evaluates to false) (0). No other possible values exist.
I know we can execute if-else together like this: if(1){ goto ELSE; } else{ ELSE: }
That works but it isn’t depending of the value of the if condition at all.

If you don't mind some undefined behavior, you can do it like this in C++:
struct J {
jmp_buf b;
};
struct backer {
backer(int v):did(v) { }
backer(backer const& o):j(o.j),did(o.did) {
o.did = true;
}
~backer() {
if(!did) {
longjmp(j.b, 1);
}
}
operator bool() {
return !did;
}
J j;
mutable bool did;
};
int main() {
if(backer b = setjmp(b.j.b)) {
std::cout << "a";
} else {
std::cout << "b";
}
}
This works fine with GCC and Clang. It works by calling setjmp on the buffer in b.j.b. That buffer is kept wrapped in a class because it can be an array, and arrays can only be copied if they are wrapped in a class. backer's constructor then takes setjmp's return value and initializes did with it. In backer's destructor that flag is tested and if it's false (first return of setjmp), it jumps back and let setjmp return a non-zero value. The destructor of backer is called when one of the branches finish.
The compiler is free to copy the backer object constructed in initializing b. If that happens, the copy constructor of it cares about setting did to true, ensuring that we jump back only one time even if the compiler didn't optimize out the backer copy during initialization.
Thus the program prints ab.

In a recursive function both branches can be executed:
void recursive(bool first)
{
if(first)
{
recursive(false);
}
else
{
//END
}
}
Invoking it with
recursive(true)
will execute the if branch followed by the else branch

First off, this isn't a stupid question :)
To understand why you can't accomplish this with any special trickery, we need to step down to the assembly that gets generated by an if-statement (particularly, the assembly for an Intel processor with gcc 4.2.1 -- different architectures will result in different assembly).
Take this simple C program:
#include <stdio.h>
int main()
{
int i;
scanf("%d", &i);
if (i == 8)
{
return 100;
}
else
{
return 3;
}
}
If the user enters a non-zero integer, we return 100; otherwise we return 3. The actual condition doesn't really matter here, because we're only interested in the assembly generated for main:
; ...
call _scanf
movl -4(%rbp), %eax
cmpl $8, %eax
jne L2
movl $100, -20(%rbp)
jmp L4
L2:
movl $3, -20(%rbp)
L4:
movl -20(%rbp), %eax
leave
ret
I'm going to assume you have no knowledge of assembly -- but don't worry, this example isn't terribly hard to keep up with. What's happening here is that we call scanf, and we compare the result of it (i) with 8.
Next, there's a Jump if Not Equal instruction to the label L2. This means that if i is equal to 8, the following instructions executed are:
Move 3 into rbp
Move rbp into eax
Leave (thereby returning the value 3 from the program).
However, if i is not equal to 8, then when we hit the jne instruction, we don't jump. Instead, we:
Move 100 into rbp
Jump unconditionally to the label L4
Move rbp into eax and end up returning 100 from the program.
With the assembly generated here, there are really only two possible branches. You can't arbitrarily reorder the code.
So would it be possible to execute both branches (when they aren't both return statements)? Yes, on the condition that your compiler is incapable of correctly producing branching code. But that would never happen on a production-level compiler.

Without devious trickery, no, this is not possible. Consider what the expression means:
if (cond) {
ifTrue;
} else {
ifFalse;
}
This says to execute ifTrue if cond is true (a non-zero value/true), and to execute ifFalse if cond is false (zero/false). Since cond can't be simultaneously true and false, you can't execute both ifTrue and ifFalse without a special case, such as goto.

You can use an integer as test variable and check its value using >,<,>=,<=,==
int x = 0;
if ( x >= 0 ) {
statement 1;
}
if ( x <= 0 ) {
statement 2;
}
In this example, both statements are only executed if x is 0. Otherwise only one of them will be.

If it is a trick question, you could answer with
if( ({ statement2; 1; }) )
statement1;
else
statement2;
Using GCC statement expressions :) For expression statements, there is the comma operator
if(expr2, 1)
expr1;
else
expr2;
This is a quite popular question.

There is no single value for x for which all paths of a conditional statement will be executed (which is kind of the point of a conditional statement; you want to execute one branch or the other based on x).
However...
In C (and C++), you could use the setjmp/longjmp facility to execute both paths of an if-else:
#include <setjmp.h>
#include <stdio.h>
jmp_buf Env;
int main(void)
{
int status = setjmp(Env);
if (status == 0)
{
printf("In status == 0 branch\n");
longjmp(Env,1);
}
else
{
printf("In status != 0 branch\n");
}
return 0;
}
The initial call to setjmp returns 0, so the first branch is taken. The call to longjmp unwinds the stack back to the point where the setjmp call returns, but this time the return value is 1 (the second argument to longjmp), so the second branch is taken. However, this is not the same thing as status evaluating to 0 and non-0 simultaneously.
In practice, it's similar to writing
for (status = 0; status < 2; status++)
{
if (status == 0)
printf("In status == 0 branch\n");
else
printf("In status != 0 branch\n");
}
although the semantics are different.
You could probably do something similarly ugly in C++ with exceptions, but I'm not enough of a C++ expert to say for sure.

For single statement cases, only one of them will be executed, not both. This is the definition of if.
HOWEVER, in the case of an if statement using compound statements (a.k.a. statement block), the compiler may optimize the code to jump from the then statements into duplicate statements in the else block.
Example:
#include <iostream>
using namespace std;
int main(void)
{
static const char common_text1[] = "Some common text here.\n";
static const char common_text2[] = "Even more common code here.\n";
if (true)
{
cout << "Condition is true.\n";
cout << common_text1; // Execution may jump to same line below.
cout << common_text2;
}
else
{
cout << "\nCondition is false.\n";
cout << common_text1; // This line and the next may be executed when the
cout << common_text2; // condition is true.
}
return 0;
}
In the above example, the compiler may generate code so that when the condition is true, the first statement in the true block is executed, then execution jumps to the common statements in the else block.
The compiler is rewriting the code:
if (true)
{
cout << "Condition is true.\n";
}
else
{
cout << "\nCondition is false.\n";
}
// The compiler factored-out the common statements.
cout << common_text1;
cout << common_text2;
This may happen when the compiler sees duplicate statements near the end of the statement block for both conditions.

switch ( x ) {
default: // if ( x )
// stuff
// no break
case 0: // else
// more stuff
break;
}
or the much simpler
if ( x ) {
// stuff
}
// more stuff

You can use this:
#include <stdio.h>
int main()
{
if (//some condition//)
{
IF:{
printf("Hello "); //Code for if block.
}
goto ELSE;
}
else
{
goto IF;
ELSE:{
printf("world");//code for else block.
}
}
return 0;
}
Output: Hello world

except goto you can use ucontext or setjmp/longjump.
you can use ucontext to switch the execute flow.
for example:
#include <stdio.h>
#include <ucontext.h>
void func(void);
int x = 0;
ucontext_t context, *cp = &context;
int main(void) {
getcontext(cp);
if (x == 0) {
printf("hello\n");
func();
} else {
printf("world\n");
}
}
void func(void) {
x++;
setcontext(cp);
}
output:
hello
world
you can also use setjmp/longjmp
#include <stdio.h>
#include <setjmp.h>
int main()
{
jmp_buf buf;
if (setjmp(buf) != 0)
{
printf("world\n");
}
else
{
printf("hello\n");
longjmp(buf, 0);
}
return 0;
}
output:
hello
world

Here's a simple example:
#include <stdio.h>
int main() {
int x;
x = 6;
if (x % 2 == 0) {
printf("Divisible by two\n");
}
else if (x % 3 == 0) {
printf("Divisible by three\n");
}
else {
printf("Not divisible by two or three\n");
}
return 0;
}
Prints
Divisible by two
NOT
Divisible by two
Divisible by three

Related

Is it possible to use continue keyword outside a loop in C++?

According to ISO C++:
The continue statement shall occur only in an iteration-statement and
causes control to pass to the loop-continuation portion of the smallest
enclosing iteration-statement, that is, to the end of the loop. More
precisely, in each of the statements
while (foo) { do { for(;;){
{ { {
// ... //.... //...
} } }
contin:; contin:; contin:;
} } while (foo); }
a continue not contained in an enclosed iteration statement is
equivalent to goto contin
Based on the last part of the quote, I thought that the following would be allowed:
#include <iostream>
using namespace std;
int main() {
continue;
cout << "Will be jumped" << endl;
contin:
}
I thought this will work as a goto statement, jumping to contin. What did I miss?
This is slight phrasing issue. What the quote means is that in
for (;;) {
{
// ...
}
contin: ;
}
The ... can be anything, including another iteration statement.
for (;;) {
{
while(foo()) {
// ...
continue;
}
}
contin: ;
}
The continue; that is not nested inside another looping construct, is going to be equivalent to goto contin;. But if it is contained, it will of course continue the internal loop, not the outer one.
Bear in mind that contin: ; is used for exposition purposes. It doesn't mean there's a literal C++-level label you can do things with.

Changing while loop to accommodate two situations

Suppose I have a while loop that depends on two separate inputs. In situation one, the while loop will take the value 1, and in situation two, it should take !cin.eof(). Is there a way I can do this efficiently? To be more concise:
string hello;
cin >> hello;
if(hello == "one")
{
//make the while loop depend on value 1
}
else if(hello == "two")
{
//make the while loop depend on value !cin.eof()
}
while(/*depends on above conditional*/)
{}
I don't want to do something like:
if(hello == "one)
{
while(1){}
}
else if(hello == "two")
{
while(!cin.eof){}
}
because the while loop essentially does the same thing in each situation.
For readability and in the interest of cohesion, I think you should move the contents of your loop into a separate function:
void DoSomething() { /* ... */ }
// ...
if(hello == "one)
{
while(1){ DoSomething(); }
}
else if(hello == "two")
{
while(!cin.eof){ DoSomething(); }
}
It's easier to see that the different while loops are doing the same thing but their conditions are different.
I believe you're looking for something like this:
while((hello == "one") || (hello == "two" && !cin.eof)) {
}
This code will do what you want, because it checks 'is the variable "one"? If so, keep executing. If it's not, it'll check: Is the variable "two"? If so, it'll check for cin.eof.
If it's neither, the loop won't execute. (the && 1 in the first condition was omitted, because it's always 'true', equalling and infinite loop)
Edit:
To simplify things, you may want to consider this code (as suggested in the comments):
bool HelloIsOne = (strcmp(hello, "one") == 0);
bool HelloIsTwo = (strcmp(hello, "two") == 0);
while(HelloIsOne || HelloIsTwo && !cin.eof) {
}
The brackets, which I placed in the previous example are actually unnecessary, because && binds stronger than ||, but they help the general clarity of the code.
Simply use or (||) as a condition in the while loop. Set the first condition if(hello == "one"). Now you have a while loop that will loop if one of the conditions is true.
bool value = hello == "one";
while (value || !cin.eof) {}
If you're using C++11:
#include <functional>
auto check = (hello == "one") ? []() bool -> { return 1; } :
[]() bool -> { return !cin.eof(); };
while(check) {
};
How about this:
switch(hello)
{
case 'one':
{
for(; 1; );
{
// your loop here
}
break;
}
case 'two':
{
for(;!cin.eof; )
{
// your other loop here
}
break;
}
default:
{
cout << " shouldnt get here unless bad user input" << endl;
break;
}
}
You can do something like this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string hello;
cin >> hello;
while(hello=="one"?1:(!cin.eof()))
{
//do stuff
}
return 0;
}
It checks if the string hello is "one" and if it's true, the condition of the while is 1, else it is !cin.eof() as you wanted.

Multiple return value method fails with goto statements

The following code:
#include <cstdlib>
#include <iostream>
using namespace std;
int function(void)
{
static int i,state=0;
switch(state)
{
case 0: goto labeL0;
case 1 :goto labeL1;
}
labeL0:
for (i = 0; i < 10; i++)
{
state=1;
return i;
labeL1:;
}
}
int main(int argc, char *argv[])
{
cout << function() << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
fails. I mean it returns only 0 instead of 0,1,2,...
I wanted just use label and goto statements to implement such functions. It is for practice (let's say homework), but I can't get it to work. Is this even possible?
How can I use goto and label statements so that this function prints 0 1 2... so on?
It's not clear to me exactly what you're trying to do. If your goal is
jsut to use goto, the simplest solution is to implement the algorithm
exactly as you'ld normally do, replacing looping constructs wit goto;
i.e. instead of:
for ( int i = 0; i < 10; ++ i ) {
std::cout << i << std::endl
}
you could write:
int i = 0;
goto label1:
label2:
std::cout << i << std::endl;
++ i;
label1:
if ( i < 10 ) goto label2;
Back in the old days, with Fortran IV, this is what we actually did.
There's absolutely no reason to do it today (except maybe obfuscation).
I wonder, however, given the static variables, if you're not trying to
implement some sort of co-routine; that each time you call the function,
you output one higher than the previous time. In this case, I'd
recommend maintaining the state in a class, rather than using static
variables. In addition the function will need some sort of return value
so that the caller will know when it's finished, and the caller will
have to loop. Something like the following should do the trick:
class CoRoutine
{
int i;
public:
CoRoutine() : i( 0 ) {}
bool function()
{
if ( i < 10 ) {
std::cout << i <<std::endl;
++ i;
}
return i < 10;
}
};
int
main()
{
CoRoutine c;
while ( c.function() ) {
}
return 0;
}
(There's still no need for goto, of course.)
This won't work since after the return statement, the compiler leaves the function ignoring all statements after it.
Also, using labels is ugly, horrible and unmaintainable. Why are you using them? Do you want the maintenance guy arriving at your house with a chain-saw?
After executing the return statement the execution returns from function().....
So initially when i=0, "return i" returns 0 and it is displayed on screen
You should use recursive call to function to get it executed and more over your use of GOTO is a typical example of why we should avoid using goto.
void function(void)
{
static int i=0;
for(;i<10;)
{
cout<<i;
i++;
function();
}
}
void main()
{
function();
}
but if you still want to use goto statements then use this
void function(void)
{
static int i =0;
lablelA:
cout<<i;
i++;
if(i == 10)
return;
goto lablelA;
}
Jumping to labeL1 is jumping in a loop with uninitialized variable i. How could this go right? This is only 1 of the reasons to avoid goto.
EDIT: actually, it should probably work as some sort of poor man's generator (because of the static local variables), but still the case of i >= 10 should be handled. Now it is returning nothing. So your main concern in the code is that you need a loop in main to call function maximum 10 times.
Still, this is not a construct I would want to see in real code.
The code reminds me of Coroutines in C.
To print 0, 1, etc you should call the function several times. That's the whole point.

Continuations/Coroutines/Generators in C++ / gcc / linux

Background: I'm trying to figure out how to implement continuations/coroutines/generators (whatever the following is called) by posing this toy problem. The environment is C++11 on gcc 4.6 and linux 3.0 x86_64. Non-portable is fine but using an external library (boost.coroutine, COROUTINE, etc) is not allowed. I think longjmp(3) and/or makecontext(2) and friends may help but not sure.
Description:
The following toy parser is supposed to parse sequences of as and bs of equal length. ie
((a+)(b+))+
such that the length of the second bracketed production equals the third.
When it finds a production (eg aaabbb) it outputs the number of as it finds (eg 3).
Code:
#include <stdlib.h>
#include <iostream>
using namespace std;
const char* s;
void yield()
{
// TODO: no data, return from produce
abort();
}
void advance()
{
s++;
if (*s == 0)
yield();
}
void consume()
{
while (true)
{
int i = 0;
while (*s == 'a')
{
i++;
advance();
}
cout << i << " ";
while (i-- > 0)
{
if (*s != 'b')
abort();
advance();
}
}
}
void produce(const char* s_)
{
s = s_;
// TODO: data available, continue into consume()
consume();
}
int main()
{
produce("aaab");
produce("bba");
produce("baa");
produce("aabbb");
produce("b");
// should print: 3 1 4
return 0;
}
Problem:
As you can see the state of the consume call stack must be saved when yield is called and then produce returns. When produce is called again, consume must be restarted by returning from yield. The challenge would be to modify the way produce calls consume, and implement yield so they function as intended.
(Obviously reimplementing consume so that it saves and rebuilds its state defeats the purpose of the exercise.)
I think what needs to be done is something like the example on the bottom of the makecontext man page: http://www.kernel.org/doc/man-pages/online/pages/man3/makecontext.3.html, but its not clear how to translate it onto this problem. (and I need sleep)
Solution:
(Thanks to Chris Dodd for design)
#include <stdlib.h>
#include <iostream>
#include <ucontext.h>
using namespace std;
const char* s;
ucontext_t main_context, consume_context;
void yield()
{
swapcontext(&consume_context, &main_context);
}
void advance()
{
s++;
if (*s == 0)
yield();
}
void consume()
{
while (true)
{
int i = 0;
while (*s == 'a')
{
i++;
advance();
}
cout << i << " ";
while (i-- > 0)
{
advance();
}
}
}
void produce(const char* s_)
{
s = s_;
swapcontext(&main_context, &consume_context);
}
int main()
{
char consume_stack[4096];
getcontext(&consume_context);
consume_context.uc_stack.ss_sp = consume_stack;
consume_context.uc_stack.ss_size = sizeof(consume_stack);
makecontext(&consume_context, consume, 0);
produce("aaab");
produce("bba");
produce("baa");
produce("aabbb");
produce("b");
// should print: 3 1 4
return 0;
}
Its fairly straight-forward to use makecontext/swapcontext for this -- you use makecontext to create a new coroutine context and swapcontext to swap between them. In you case, you need one additional coroutine to run the consume infinite loop, and you run main and produce in the main context.
So main should call getcontext+makecontext to create a new context that will run the consume loop:
getcontext(&consume_ctxt);
// set up stack in consume_context
makecontext(&consume_ctxt, consume, 0);
and then produce will switch to it instead of calling consume directly:
void produce(const char* s_)
{
s = s_;
swapcontext(&main_ctxt, &consume_ctxt);
}
and finally yield just calls swapcontext(&consume_ctxt, &main_ctxt); to switch back to the main context (which will continue in produce and immediately return).
Note that since consume is an infinite loop, you don't need to worry too much about what happens when it returns (so the link will never be used)

Is "} while (0);" always equal to "break;} while (1);"?

I have compared gcc assembler output of
do {
// some code
} while (0);
with
do {
// some code
break;
} while (1);
The output is equal, with or without optimization but..
It's always that way?
No experiment can prove theories, they can only show they are wrong
There is a slight difference:
do {
// code
if ( condition )
continue;
// code
break;
} while(1);
Will restart the loop when condition is true, whereas in the } while(0); version, the continue will be equivalent to break.
If no continue is present, then they should produce exactly the same code.
The forms are not equivalent. This is an infinite loop:
do {
continue;
break;
} while (1);
This isn't:
do {
continue;
} while (0);
Edit: Upon reading various comments on the matter, I will admit that this answer is wrong. Sorry.
Instead of:
do{
//some code
}while(0);
or:
do{
//some code
break;
}while(1);
I would just use:
//some code
I'm not 100% sure if you can do this in c++, but if you want to limit the scope of variables, and that is why you are doing this, just use curly braces by themselves:
{
// Some Code
}
Markus' comment pointed me to this answer: the difference is when using continue keyword.
In this case:
int _tmain(int argc, _TCHAR* argv[])
{
int i = 0;
do {
++i;
_tprintf(_T("Iteration %d\n"), i);
if (i < 30) continue;
} while(0);
return 0;
}
you get only one iteration, while in this case:
int _tmain(int argc, _TCHAR* argv[])
{
int i = 0;
do {
++i;
_tprintf(_T("Iteration %d\n"), i);
if (i < 30) continue;
break;
} while(1);
return 0;
}
you get 30 iterations. Tested under VS2008.
The do while clauses are logically equivalent. If they are translated to the same byte code depends on the compiler at hand. I guess that most modern compilers will treat them equally.
EDIT based on your comment that you're using a while with breaks in order to be able to break out of the 'loop' when certain conditions have been met.
If this is what you're trying to accomplish:
do
{
// processing step 1
if( some_condition )
break;
// processing step 2
if( some_condition )
break;
// etcetera..
} while(0)
...then just break the code you have in your while loop out to a stand-alone function with multiple returns:
void processing()
{
// processing step 1
if( some_condition )
return;
// processing step 2
if( some_condition )
return;
// etcetera..
}
int main()
{
// ...
processing();
return 0;
}