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

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;
}

Related

how to replace a value of a variable inside code from user input?

i am trying to add a developer mode in my program. since duty of car defers every month,i want give my user permission to change every single variables in my program alike duty lccost yen2taka freight
#include <iostream>
using namespace std;
class A
{
public:
int carbid,duty;
void Input()
{
cout<<"please insert the car price you want to bid for(in yen): ";
cin>>carbid;
cout<<"duty of the car: ";
cin>>duty;
}
int Exportcost()
{
int exportcost;
int servicechrg=10;
int freight=20;
exportcost=servicechrg+freight+carbid;
return exportcost;
}
int Yen2taka()
{
int yen2taka;
int taka2dollarrate=10;
int dollar2yen=1;
yen2taka=((Exportcost())/dollar2yen)*taka2dollarrate;
return yen2taka;
}
int Importcost()
{
int importcost;
int lccost=10;
int cnfcost=20;
importcost=lccost+cnfcost;
return importcost;
}
int Totalcosting()
{
int total;
int myprofit=10; //80000
total=myprofit+Importcost()+Yen2taka();
cout<<total;
return total;
}
void summary()
{
cout<<
}
};
int main()
{
x:
A ob;
ob.Input();
ob.Exportcost();
ob.Yen2taka();
ob.Importcost();
ob.Totalcosting();
int ch;
cout<<"press 1 to see the summery of the costing or 2 to restart costing again"<<endl;
cin>>ch;
switch(ch)
{
case 1:
ob.summary();
break;
case 2:
goto x;
}
}
At first, you should collect these parameters in a separate class:
class Configuration // maybe you find a better name...
{
int m_servicechrg = 10; // default
int m_freight = 20;
// ...
public:
int servicechrg() { return m_servicechrg; }
void servicechrg(int value); { /* check some limits? */ m_servicechrg = value; }
int freight() { return m_freight; }
void freight(int value); { /* check some limits? */ m_freight = value; }
// ...
};
// will allow you to do:
// C c; std::cout << c;
ostream& operator<<(ostream& s, Configuration const& c)
{
// which ever formatting is appropriate...
s << c.servicechrg() << ' ' << c.freight();
return s;
}
The setters could alternatively return bool to indicate invalid values.
Now you can use this class within main:
Configuration c;
A a;
int cost = a.exportCost(c); // you'd have to adjust signatures...
int value;
switch(ch)
{
case 4:
if(stc::cin >> freight) // catches invalid user input!
// one ALWAYS should do, otherwise you might end up in
// your program not working any more
{
c.freight(value);
// or, if you have:
if(!c.freight(value))
{
// some appropriate error message
// (it's better not to output in the setter, you are more flexible this
// way – maybe you want different messages at different occasions?)
}
}
else
{
// appropriate error handling
}
break;
default:
// handling invalid user input
// again, you always should; but stream state is not in error state,
// so you just can print appropriate error message
break;
}
See this answer for how to correctly handle stream errors.
If you wonder about the differences in error handling: First case is met if user enters non-numerical input, such as ss, second case, if input is numerical, but out of valid range (77).
Now if you don't want to pass the configuration as parameter all the time, you could make a global variable from (but careful, there are some dangers with global variables, use them as sparely as possible) or implement the singleton pattern.
Side notes: goto can be a fine tool sometimes, but it is a dangerous one (and the label's name x isn't a good one, prefer a name that clearly shows intention, such as REENTRY_POINT, LOOP_START, ...). If you can get along without unreasonable effort, prefer such variants:
bool isRunning = true;
do
{
// ...
case 2:
isRunning = false;
break;
}
while(isRunning);
Sure, an additional variable, an additional check; unfortunately, you cannot use break to exit a (pseudo-) endless loop (for(;;)) (but don't apply this pattern for nested loops, then it gets more and more unreadabla – and ineffcient: bool isExit = false; for(int i = 0; !isExit && i < n; ++i) { for(j = 0; j < n; ++j) { isExit = true; break; } } – see what I mean?). A variant might be:
for(;;)
{
switch(ch)
case 1:
// ...
//break; <- replace
continue;
case 2:
//
break;
} // end of switch
break; // break the surrounding for(;;) loop
}
But that's not really nice either.
A pretty nice variant allowing to exit the loop in the given case, as there isn't anyhting to do afterwards:
for(;;)
{
switch(ch)
{
case 2:
// maybe yet some cleaning up here
return 0;
default:
// ...
break;
}
}
Drawback: The function's exit point possibly is deeply nested inside the code.
There are yet other tricks to allow this pattern, like packing sub-sections of code in a lambda having a return inside and call that one directly. But that now really starts going beyond the scope...
Finally, if you insist on goto, my variant would rather be:
for(;;)
{
switch(ch)
{
case 2:
// ...
goto LOOP_EXIT;
default:
// ...
break;
}
}
LOOP_EXIT:
return 0; // e. g. main
(void)0; // if there isn't anything to do in the function any more
// (labels require an instruction afterwards!)
There won't be a hidden loop now and it is more obvious what you actually are doing. Currently, not really an issue, but if your code grows, the hidden loop gets more and more difficult to spot.
In such cases, I clearly mark the gotos so that another coder can immediately spot the critical code points:
///////////////////////////////////////////////////
// possibly some comment why applying this pattern
goto SOME_LABEL;
///////////////////////////////////////////////////
One could do the same with deeply nested function exit points (return).

Jumping from a scope

Is it possible to jump from an unnamed scope?
void MyFunc() {
{
... // Code
if (!head_size) {
goto _common_error; // <- break and continue don't work here
}
... // Code
if (!tail_size) {
goto _common_error; // second time
}
... // Code
}
_common_error:
{
... // Code
}
}
My question is not whether this can be redesigned, but whether there is a trick in c++ that I don't know.
Is there a mechanism in c++ other than goto to jump out of an unnamed scope? break and continue do not work in scopes.
Update1: changed word namespace to scope
Yes, you need to use goto to jump out of a scope.
break can only be used to jump out of a loop or switch.
But you can use a (questionable) trick by using a dummy loop:
void MyFunc() {
do {
... // Code
if (!head_size) {
break;
}
... // Code
if (!tail_size) {
break;
}
... // Code
} while (false);
{
... // Error handling code
}
}
Using macro magic
#define BREAKABLE_SCOPE() for (char __scope = 0; __scope == 0; __scope++)
You can then do
int main()
{
// Will only print "Hello!"
BREAKABLE_SCOPE()
{
printf("Hello!");
break;
printf("Hello again!");
}
return 0;
}
Please note that macros will reduce the readability of your code.

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.

What's better in that context - `for` or `while`

I've read somewhere that one should use a for loop when you are iterating over some sort of array/sequence/list/whatever you call it and a while loop when your loop needs to stop at a certain condition.
So, what if I have something like this
int len = 0;
for(; s[len] != '\n'; ++len) {
// some processing
if (someCondition) {
return len;
}
}
// if done iterating, return len
return len;
Is this okay to use the for loop in this context or would a while loop be preferable?
I'd probably write it this way:
int len;
for (len = 0; s[len] != '\n'; ++len) {
...
}
return len;
Just because then I say in the for statement what the range is I'm interested in (index 0 up to the first newline character).
I generally choose between for and while on the basis of what the code looks like, rather than on where I stand in the hairsplitting semantics argument what the difference is between "some kind of range" vs "the period from now until some condition is false". I don't think it's a problem to play around a bit with for. The third part of the statement is "specially visible" in the way that an increment at the end of a while loop isn't, and I think that's enough to justify using it with a minor contortion like your empty first part.
The for loop is OK. You have the increment ++len at the place of loop control, which I find preferable. You don't forget it somewhere at the end of the loop body. And it even works well when you use continue.
Well, a for loop is the only one that's going to accept that kind of syntax so that's what I'd say you should use. Besides that...it actually doesn't really matter in the slightest. Do what is easy to read.
Given your quoted code, I'd use a for loop, but I would put the initializer inside the for statement as an assignment:
int len; // <== Not here
for (len = 0; s[len] != '\n'; ++len) { // <== Here
// some processing
if (someCondition) {
return len;
}
}
This is exactly what the for structure is for: An initialization, test, and increment.
I would use a While and put the len incrementation inside the condition verification s[++len] != '\n' :D
But I guess it's what flavour you prefer really :)
You're iterating, and a for loop is more compact. You can achieve the same thing in either case anyway, but for this I prefer to use for because you have all the loop drivers (condition, counter increase) in the beginning.
int len = 0;
while (s[len] != '\n')
{
// do stuff
if (something) return len;
++len;
}
return len;
vs.
int len;
for (len = 0; s[len] != '\n'; ++len)
{
// do stuff
if (something) return len;
}
return len;
It is a matter of taste. Both are equivalent.
But with years I have happend to really prefer the while loop over for loop. I prefer when lines are short, and the for has a tendency to put 3 different steps in the same line.
int i=0;
while(s[i] != '\n')
{
// some processing
if (someCondition)
{
return i;
}
++i;
}
but as i said, it's a matter of taste.
Personally, I'd go with this:
int len = 0;
for (; s[len] != '\n'; ++len) {
// some processing
if (someCondition) {
break;
}
}
// if done iterating, return len
return len;
But really, it's all down to readability, as there's no real semantic difference between for and while loops. Use whatever format you feel conveys the meaning of your code the best. In the above case I chose for because of the len loop variable, if that wasn't there I would have went with while.
It really doesn't matter. They are equivalent in terms of efficiency. You could do either of the following:
for(; s[len] != '\n'; len++) { ... }
while(s[len] != '\n') { ... len++; }
The for loop is perhaps more easily readable in this case, and the while is perhaps a bit more clever, but they're really functionally equivalent.
EDIT: True, the for doesn't increment the counter until after the first loop. Fixed it.
I see majority of the post are using for.
This post here will give you idea in case you want to pursue with while.
#include <stdio.h>
main ()
{
int counter=0;
while(somecondition) {
if (s[counter]!='\n')
{
//some processing
}
++counter;
}
}
return len;
What about foreach!
int len = 0;
for each (char& c : s) {
// some processing
if (someCondition || c=='\n') break;
len++;
}
// if done iterating, return len
return len;

Simultaneous execution of both if and else blocks

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