This question already has an answer here:
Fortran IF statement with numbers/labels rather than another statement
(1 answer)
Closed 7 years ago.
I'm trying to teach myself fortran so I can unravel an old program and repurpose it for our own use. I can't figure out what this statement does:
if(s - fm) 198, 198, 197
s - fm isn't a condition that can be true or false, right?.
And when it passes control to the line marked 198, does it then continue to the end of the program? How does it know when to come back to execute 198 again and then 197?
This is an "archaic" form of IF:
IF (''arithmeticExpression'') ''firstLineNumber'', ''secondLineNumber'', ''thirdLineNumber''
In the second form, the arithmetic expression is evaluated. If the expression evaluates to a negative number, then execution continues at the first line number. If the expression evaluates to zero, then execution continues at the second line number. Otherwise, execution continues at the third line number.
It's a "three-way goto" depending on the sign of the expression.
In a more traditional C-like language it wood be
/* IF(a) label1, label2, label3 */
if(a > 0)
{
goto label3;
} else
if(a < 0)
{
goto label1;
} else
{
// a == 0
goto label2;
}
Your case contains two labels 198 which works like
if(s <= fm) { goto lbl198; } else { goto lbl197; }
Ref: wikibooks
This obsolete feature puzzles a lot of people:
FORTRAN compiler warning: obsolete arithmetic IF statement
Fortran strange IF
strange label usage
Related
This question already has answers here:
If statements without brackets
(3 answers)
Closed 10 months ago.
Does the indentation in an if else statement have any bearing on the execution of the code or is it just something to do for cleaner code?
Example from the book Accelerated C++ written by Andrew Koening:
while(c != cols) {
if(r == pad + 1 && c == pad + 1) {
cout << greet;
c += greet.size();
} else {
if(r == 0 || r == rows - 1 || c == 0 || c == cols - 1)
cout << "*";
else
cout << " ";
++c;
}
}
The prefix increment of c is executed regardless of whether r=0 or not, but I don’t understand why.
If the if statement turns true, an asterisk is printed. If not, a blank space is printed and c is incremented.
That’s how I am reading it, but c gets incremented regardless of what the values of r or c are.
This is what it says in the book, but there isn’t any explanation I could find:
Notice how the different indentation of
++c;
draws attention to the fact that it is executed regardless of whether we are in the
border.
Whitespace does not affect C++ runtime behavior. (Unlike certain other languages, like Python).
I should mention that in your else block, you do not use braces. So, only the first statement (cout << " ";) will be part of the else clause. The subsequent ++c; will execute regardless of the value of r and c.
Note that this last point is subjective, so take it with a grain of salt... As you can see, when braces are omitted from if ... else ... blocks, there is potential for confusion. Some would argue that it leads to more concise code, but many (including myself) would argue that you should always use braces. This is especially important when you work on a large team because code tends to grow over time. I've seen many cases in production code where an if statement was missing the braces and someone added a second line to the if clause without remembering to add braces. This didn't work as expected and caused wasted time debugging fails, just because the braces were omitted.
Both C and C++ are not affected by white space in their interpretation of the code. That does not mean the programmer should not care about its misuse.
The best way to illustrate what the above code actually represents is to explicitly define all of the inferred braces as below. Note that the if statement that had no braces only has one line of code affected by the 'if then' or 'else' clause.
This is one of the reasons that people try to insist on
'good coding practices' to ensure that other people are able to clearly interpret the flow and intent of the programmer.
while(c != cols) {
if(r == pad + 1 && c == pad + 1) {
cout << greet;
c += greet.size();
} else {
if(r == 0 || r == rows - 1 || c == 0 || c == cols - 1) {
cout << "*";
} else {
cout << " ";
}
++c;
}
}
In C++ the length of indentation does not affect the interpretation of the statements. Sometimes whitespace is needed to separate characters, e.g., in int a. Other times it is not needed, e.g. in a=b+c;.
The if statement is defined that after the condition if(condition) can only be one statement.
If we want more statements we have to group them with braces {...}
Unlike Python, C++ does not care about indentation.
But your else applies only on the first line. To apply to a block, it should be within { }
else
{
cout << " ";
++c;
}
Indentation is not your problem here.
I am new to C++ and I have a problem where i have to transform a pseudocode in C++ / C / Pascal language. The answer at the end of the book written in Pascal.
The problem in my C++ code is that at the line 12, I get the error which can be found in the title. Any idea?
Pascal Code:
var n,x:integer;
begin
n:=0;
repeat
write('x=');read(X);
if x<>0 then
if x mod 5 = 0 then
n:=n+1
else
n:=n-1;
until x=0;
if n=0 then
write('yes')
else
write('no')
end;
My C++ Code:
int main()
{
int x,n;
cin>>x;
while(x>0)
{
if(x>0)
{
if(x%5=0){
n=n+1;
} else {
n=n-1;
}
}
if(n=0){
cout<<"Yes"<<;
} else {
cout<<"No"<<;
}
}
}
You have a simple typo: if(x%5=0){ is an attempt to assign 0 to x % 5 (due to operator precedence modulus is computed before assignment). x % 5 cannot be assigned to (it's not an lvalue) and the compiler is telling you that.
The fix, of course, is to write x % 5 == 0.
You're lucky in this case that the error is picked up at compile-time. Something like if (n = 0) (on line 18) might not be, since x = 0 is an expression with value 0.
Two ways to guard against that:
Ensure that your compiler warnings are as aggressive as you can bear. With gcc, I use -Wall -Wextra, and that combination is enough to catch this common problem.
Some developers will write if (0 == x) since an errant if (0 = x) would be picked up at compile time as an attempt to assign to 0. Personally, I find that obfuscating.
Assignment operator requires lvalue means the left side operand need to be a variable/location that can hold a value.
This is what is meant by the error.
What you need in your if statement is == likely not assignment as mentioned by other answers
You need to use == in conditions (while, if, ...) for equality check in C++.
if(x%5 = 0)
should be
if(x%5 == 0)
"x%5" is not an lvalue in that you can not assign a value to it, hence the error.
while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
I came across this on codegolf
Please explain the usage of ? and : and why is there no statement following the while loop? As in why is there a ; after the parenthesis.
There is a boolean operation going on inside the parentheses of the while loop:
while (boolean);
Since the ternary operator is a boolean operator, it's perfectly legal.
So what's this doing? Looks like modular arithmetic, printing going on over a range up to 101.
I'll agree that it's cryptic and obscure. It looks more like a code obfuscation runner up. But it appears to be compilable and runnable. Did you try it? What did it do?
The ?: is a ternary operator.
An expression of form <A> ? <B> : <C> evaluates to:
If <A> is true, then it evaluates to <B>
If <A> is false, then it evaluates to <C>
The ; after the while loop indicates an empty instruction. It is equivalent to writing
while (<condition>) {}
The code you posted seems like being obfuscated.
Please explain the usage of ? and :
That's the conditional operator. a ? b : c evaluates a and converts it to a boolean value. Then it evaluates b if its true, or c if its false, and the overall value of the expression is the result of evaluating b or c.
So the first sub-expression:
assigns t-i%10 to i. The result of that expression is the new value of i.
if i is not zero, the result of the expression is i/10
otherwise, print j, and the result of the expression is zero (since printf returns a non-zero count of characters printed, which ! converts to zero).
Then the second sub-expression, after ||, is only evaluated if the result of the first expression was zero. I'll leave you to figure out what that does.
why is there no statement following the while loop?
There's an empty statement, ;, so the loop body does nothing. All the action happens in the side effects of the conditional expression. This is a common technique when the purpose of the code is to baffle the reader; but please don't do this sort of thing when writing code that anyone you care about might need to maintain.
This is the Conditional Operator (also called ternary operator).
It is a one-line syntax to do the same as if (?) condition doA else (:) doB;
In your example:
(i=t-i%10 ? i/10 : !printf("%d\n",j)
Is equivalent to
if (i=t-i%10)
i/10;
else
!printf("%d\n",j);
?: is the short hand notation for if then else
(i=t-i%10 ? i/10 : !printf("%d\n",j)<br>
equals to
if( i= t-i%10 )
then { i/10 }
else { !printf("%d\n",j) }
Your while loop will run when the statement before the || is true OR the statement after the || is true.
notice that your code does not make any sense.
while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
in the most human-readable i can do it for u, it's equivalent to:
while (i < 101)
{
i = (t - i) % 10;
if (i > 0)
{
i = i / 10;
}
else
{
printf("%d\n",j);
}
i = ++j;
if (i < 0)
{
i = i - j;
}
else
{
i = j;
}
}
Greetings.
I am the proud perpetrator of that code. Here goes the full version:
main()
{
int t=getchar()-48,i=100,j=-i;
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
}
It is my submission to a programming challenge or "code golf" where you are asked to create the tinniest program that would accept a digit as a parameter and print all the numbers in the range -100 to 100 that include the given digit. Using strings or regular expressions is forbidden.
Here's the link to the challenge.
The point is that it is doing all the work into a single statement that evaluates to a boolean. In fact, this is the result of merging two different while loops into a single one. It is equivalent to the following code:
main()
{
int i,t=getchar()-'0',j=-100;
do
{
i = j<0? -j : j;
do
{
if (t == i%10)
{
printf("%d\n",j);
break;
}
}
while(i/=10);
}
while (j++<100);
}
Now lets dissect that loop a little.
First, the initialisation.
int t=getchar()-48,i=100,j=-i;
A character will be read from the standard input. You are supposed to type a number between 0 and 9. 48 is the value for the zero character ('0'), so t will end up holding an integer between 0 and 9.
i and j will be 100 and -100. j will be run from -100 to 100 (inclusive) and i will always hold the absolute value of j.
Now the loop:
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
Let's read it as
while ( A || B ) /* do nothing */ ;
with A equals to (i=t-i%10?i/10:!printf("%d\n",j)) and B equals to (i=++j<0?-j:j)<101
The point is that A is evaluated as a boolean. If true, B won't be evaluated at all and the loop will execute again. If false, B will be evaluated and in turn, if B is true we'll repeat again and once B is false, the loop will be exited.
So A is the inner loop and B the outer loop. Let's dissect them
(i=t-i%10?i/10:!printf("%d\n",j))
It's a ternary operator in the form i = CONDITION? X : Y; It means that first CONDITION will be evaluated. If true, i will be set to the value of X; otherwise i will be set to Y.
Here CONDITION (t-i%10) can be read as t - (i%10). This will evaluate to true if i modulo 10 is different than t, and false if i%10 and t are the same value.
If different, it's equivalent to i = i / 10;
If same, the operation will be i = !printf("%d\n",j)
If you think about it hard enough, you'll see that it's just a loop that checks if any of the decimal digits in the integer in i is equal to t.
The loop will keep going until exhausting all digits of i (i/10 will be zero) or the printf statement is run. Printf returns the number of digits printed, which should always be more than zero, so !printf(...) shall always evaluate to false, also terminating the loop.
Now for the B part (outer loop), it will just increment j until it reaches 101, and set i to the absolute value of j in the way.
Hope I made any sense.
Yes, I found this thread by searching for my code in google because I couldn't find the challenge post.
printf("What do you do?\n1. Walk Away.\n2. Jump.\n3. Open Door.\n\n");
scanf("%d",&Choice);
printf("\n\n\n");
while(4<=Choice,Choice<=0);
{
printf("That is not a choice.\n");
printf("What do you do?\n1. Walk Away.\n2. Jump.\n3. Open Door.\n\n");
scanf("%d",&Choice);
printf("\n\n\n");
}
So this is my program. It works but what I want it to do is to repeat until an answer of 1, 2, or 3 is put in. But no matter what the answer is it has it go through the while loop then continue regardless of the next choice. (Also, I did declare "Choice"; I just didn't want to show the whole program.)
There are two problems in your code. Your while-loop expression is incorrect. The comma does not do what you think it does: in C/C++, the comma executes the left-hand expression and evaluates to the right-hand expression, meaning that in your case you are only checking the second condition. You probably want:
while(4<=Choice || Choice<=0)
The || is the OR operator, which returns true if either of the expressions around it are true.
Secondarily, there is a misplaced semicolon at the end of the while loop:
while(4<=Choice,Choice<=0); //<-- this should not be here
This marks the end of the loop, meaning that your code is parsed as:
while(4<=Choice,Choice<=0); //loop body is empty
{
//and we have a random unnamed block following it
}
Remove the semicolon and your while loop should execute correctly.
C and C++ have a comma operator, which has the lowest precedence of all operators. It evaluates the left operand and throws the result away, and then evaluates the right operand. Thus, your while condition is equivalent to:
while (Choice <= 0)
You also have a bug because there is a semicolon immediately after the condition, which makes for an infinite loop if Choice is not strictly positive (because nothing in the loop changes the value of Choice).
What you probably intended to write was:
while (Choice >= 4 || Choice <= 0)
{
...
}
The comma operator , doesn't test both conditions, it simply returns the second of the two. So your while loop is the equivalent of:
while(Choice<=0) ;
and since there's a ; following the statement, it is in fact an infinite loop if the condition is met. Good thing you didn't enter a choice of -1.
Pretty much what the title says. I'm to the last bit of this lottery numbers assignment, and I'm not sure why the second set of if/else if statements aren't displaying when I debug. I know that if/else statements are mutually exclusive - but shouldn't an if and then another if both test?
Here's the code.
count=0;
while(count<5)
{
if(lottery[count] == user[count])
{
lotto = lottery[count];
cout<<"So, you matched numbers with "<<lotto <<".\n";
tally++;
}
if(tally==5 && count == 5)
{
cout<<"Congratulations, you're the grand prize winner!";
}
else if(tally < 5 && count == 5)
{
cout<<"A total of "<<tally<<" of your lottery picks matched.";
}
else if(tally == 0 && count == 5)
{
cout<<"Caution. The following comment is an inside joke. Read at your own risk.";
cout<<"Bet you feel like a total loser huh? Nothing matched.";
}
count++;
}
I know I probably ought to have replaced the while loop with a for loop for simplicity's sake but i'm more comfortable with the while.
count will never be 5 when the if blocks are executed.
As soon as it becomes 5, the condition fails and the loop stops.
count will never be equal to 5 inside the while loop at the point where your if-else conditions require it. If you had incremented count before the if-else then it would have been possible to satisfy one of the conditions (depending on the value of tally).