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.
Related
I am attempting to solve a hw problem in which I need to write down what the program will output. I am stuck however, on the syntax "if ( !(i%3)). What does that really mean? Does it mean that the program is checking for any i that is divisible by three? aka, is the if statement only runs if i is divisible by three?
int main () {
for (int i=0; i<10; (i<3?i++;i+=2)) {
if (!(i%3)) {
continue;
}
else if (i%7 ==0) {
break;
}
cout << i<< endl;
}
Does it mean that the program is checking for any i that is divisible by three? aka, is the if statement only runs if i is divisible by three?
Correct. The longer version of that check would be
if (i % 3 == 0)
continue;
The most common use case for such branching is probably FizzBuzz.
İt means if i is not(!) divisible by 3 continue.
For example if i is 3,6,9 it won't continue otherwise it will continue.
if (x) where x is int implicitly compared with zero. I.e. if (x) equals to if (x != 0). ! is negation. So if (!x) equals to if (x == 0). And the last step is if (!(i%3)) equals to if ((i%3) == 0) what is the same with check, that i deivisible by 3
The if() statement is false only if the result inside the parentheses is 0 (false). Take a look at your program:
i%3 may return 0 (false), 1 (true), or 2 (true)
The negation operator ! changes the result of the operation (i%3). So, if the i is divisible with 3 the statement will return 0 (false). Being negate, ! it will result in True. Otherwise the result of (i%3) will be true and with the operator ! the result of the hole statement will be false. Basically this code is checking if the value of i is divisible with 3.
Other options will be:
if (0==i%3)
{
/*code*/
}
Your code can be simplified as below
int main() {
for (int i=0; i<10;)
{
if (i % 3 == 0) {
continue;
}
else if (i % 7 == 0) {
break;
}
cout << i << endl;
i = i<3 ? i+1 : i+2;
}
}
When you write a integer variable like i as a condition, what happens is that if i==0 then the result of the condition is false, otherwise it would be true.
Let's check it out in your program, if(!(x%3)), let's name condition= !(x%3), when this condition is true? when x%3 == 0, note that the negation operator ! is behind x%3, so in this case the condition would be equal to true, more formally the condition is equal to :
if(x%3==0)
these kinds of conditions are common, check this example out :
int t = 10;
while(t--){
cout<<t<<endl;
}
The above condition i.e if(!(i%3)) will true when " i is not disvisable by 3"
Hope this helps.
In java and other languages there is a special type to represent booleans and evaluate expressions; in c and its variants there is no such thing, instead an expression is considered "true" if -taken as a integer number- is equal to 0; false for every other value. (Fun fact: this is why you usually end the code by return 0)
So if(x%3) in c is equivalent to if(x%3==0) in other languages. That said, if(x%3) execute the if body when the remainder of x/3 is 0, that is when x is a multiple of 3.
In your code you have the ! before, that -as you may know- "inverts" the expression. That means that if(!(x%3)) can be read as "If the remainder of the integer division of x by 3 is not 0", or alternatively: "If x is not a multiple of 3".
So, basically, you saw it right.
Hope I helped!
How can I convert C code to C++? When I try my best, I failed every time.
Can anyone help me?
In particular, I'm trying to understand the following:
v=v%10?v%(5*r)*n--:v/10
I know if v == v mod 10,v%(5*r)*n--. if not, v/10. But I don't understand v%(5*r)*n--.
Here's the code in context:
long v=1,r=1e9;
main(n){
for(scanf("%d",&n);v=v%10?v%(5*r)*n--:v/10;n||printf("%d",v%r));
}
This C expression is also valid in C++. Expression v%(5*r)*n-- is equivalent to expression v % ((5*r)*(n--)) due to operator precedence rules. Postfix decrement operator --(it decreases a variable by one) will evaluate first, what remains is an expression of type A % B * C. Since operators % (remainder) and * (multiplication) are on the same precedence level, left to right associativity rule will be applied. Therefore, we have v % ((5*r)*(n--)). For more information check out these links:
http://en.cppreference.com/w/cpp/language/operator_precedence
https://en.wikipedia.org/wiki/Operator_associativity
You also do no understand the ternary operator. In your case, the whole statement v=v%10?v%(5*r)*n--:v/10 means: if v%10 is true (different from zero) then assign result of v%(5*r)*n-- to variable v, otherwise assign result of v/10 to variable v. For more information check out
http://www.cprogramming.com/reference/operators/ternary-operator.html
Btw, please note that the person writing this blog produces some awful code. You probably do not want to learn from it.
Your definition for main is bad. C++ does not allow implicit typing for functions1, and main takes either zero or two arguments; it should be written as
int main( int argc, char **argv )
{
...
}
if the program takes any command line arguments2 and
int main( void )
{
...
}
if it doesn't3.
The expression v=v%10?v%(5*r)*n--:v/10 is equally valid (if unspeakably ugly) in C and C++, so that's not an issue.
The expression n||printf("%d",v%r) is a bit of a head-scratcher, though; what do you think it's trying to accomplish?
Edit
Sorry, wasn't quite awake when I wrote that last bit. Obviously, the intent of that expression is to only write the value of v%r when n is 0.
The || is the logical-or operator - the expression a || b evaluates to 1 if either a or b is non-zero, or 0 if both a and b are zero. The operator short-circuits; if a is non-zero, then the result of a || b is 1 regardless of the value of b, so b won't be evaluated at all.
Thus, in the expression n || printf( "%d", v%r ), if n is non-zero, then the printf call won't be executed.
Note that the line
for(scanf("%d",&n);v=v%10?v%(5*r)*n--:v/10;n||printf("%d",v%r));
is hideous; even with some whitespace it would be hard to follow and debug. This should not be taken as an example of good code. That style of programming is only suitable for the IOCCC, except that it's not ugly enough for that particular competition.
A better way to write it for C++ would be
#include <iostream>
int main( void )
{
long v=1,r=1e9; // no reason to make these global
int n;
if ( std::cin >> n )
{
while ( v ) // v != 0
{
if ( v % 10 )
v = v % (5 * r) * n--; // whitespace is your friend, use it
else
v = v / 10;
if ( n ) // n != 0
std::cout << v % r;
}
}
else
{
std::cerr << "Error while reading \"n\"...try again" << std::endl;
}
return 0;
}
1. Neither does C since the 1999 standard, and it's bad practice anyway.
2. You don't have to use the names argc and argv, although they are the common convention.
3. Implementations may provide additional signatures for main (such as extra arguments in addition to argc and argv), but those additional signatures must be documented; don't assume any random signature is going to be valid.
Is it possible to write a one line if-else statement (i.e. only using one ;) without using the ?: expression? For instance something of the form:
if (p == 1) " " else "\n";
Potential purpose could be:
cout << if (p == 1) " " else "\n";
Just curious if this is possible, don't know if there are any practical applications for this.
Thanks
You're asking "how do I do X, without using any of the tools the language provides to do X". It's silly.
And the answer's no. It's not possible.
This doesn't address the general question, but it does work for the specific example you provided.
std::cout << " \n"[(bool)(p - 1)];
Explanation:
First, a string literal (such as " \n") is an array. As such, it participates in pointer decay, and can be indexed just like any other pointer or array.
Second, an integer can be converted to a bool, and the conversion has the special property that a zero is converted to false, and anything else is converted to true. So when I subtract 1 from p, then convert it to bool, it is false if p is 1, and true otherwise.
Third, a bool can be (implicitly) converted back to an integer. false converts to 0, and true converts to 1. So converting from an int to a bool and back has the result that a 0 stays a 0, and anything else becomes a 1.
So, with those three points taken into consideration, the expression:
" \n"[(bool)(p - 1)]
results in one of these two possibilities:
" \n"[0] // a space (if p == 1)
" \n"[1] // or a newline (if p != 1)
I'd downvote this answer if I could.
You already used the two important words that are key to undestand why what you intend is not possible, but you probably haven't grasped their full meaning: Statement and expression.
The if statement (like all statements) does not yield a value, while the ?: operator is an expression that does yield a value.
Distinguishing between statements and expressions is a fundamental concept that is worth learning (check out the links in this answer and take your time!), not just for C++ but for almost all programming languages.
cout << [=]{ if (p == 1) return " "; else return "\n"; }();
Basically: no, it's not possible to do this:
cout << if (p == 1) " " else "\n";
That is exactly the purpose of ?: operator - it yields value. Some things may not be possible with if-else syntax. Example: conditional initialization. Consider:
if(p == 1)
int value = 1; //local variable!
else
int value = 0; //and so is this one!
//here 'value' is unknown
Above problem could be solved this way:
int value; //default initialization
if(p == 1)
value = 1; //assignment to already initialized variable!
else
value = 0; //and so is this!
But these two are not equal. For some types, it may result in totally different behavior, because initialization is different from assignment. ?: is a solution:
int value == (p == 1) ? 1 : 0; //'value' is initialized with value, that depends on 'p'
Do not try to do things without tools, that were designed to do that things for you.
This question already has an answer here:
The Definitive C++ Book Guide and List
(1 answer)
Closed 7 years ago.
I'm less than a year into C++ development (focused on other languages prior to this) and I'm looking at a guy's code who's been doing this for two decades. I've never seen this syntax before and hopefully someone can be of some help.
bool b; // There exists a Boolean variable.
int i; // There exists an integer variable.
sscanf(value, "%d", &i); // The int is assigned from a scan.
b = (i != 0); // I have never seen this syntax before.
I get that the boolean is being assigned from the int that was just scanned, but I don't get the (* != 0) aspects of what's going on. Could someone explain why this person who knows the language much better than I is doing syntax like this?
Have a read here:
http://en.cppreference.com/w/cpp/language/operator_comparison
The result of operator != is a bool. So the person is saying "compare the value in i with 0". If 'i' is not equal to 0, then the '!=' returns true.
So in effect the value in b is "true if 'i' is anything but zero"
EDIT: In response to the OP's comment on this, yes you could have a similar situation if you used any other operator which returns bool. Of course when used with an int type, the != means negative numbers evaluate to true. If > 0 were used then both 0 and negative numbers would evaluate to false.
The expression (i != 0) evaluates to a boolean value, true if the expression is true (i.e. if i is non-zero) and false otherwise.
This value is then assigned to b.
You'd get the same result from b = i;, if you prefer brevity to explicitness, due to the standard boolean conversion from numeric types which gives false for zero and true for non-zero.
Or b = (i != 0) ? true : false; if you like extraneous verbosity.
(i != 0) is an expression that evaluates to true or false. Hence, b gets the value of true/false depending on the value of i.
This is fairly fundamental syntax. The != operator performs a "not equal to" comparison.
You may be being confused by the shorthand of initialising a bool directly from the result of a comparison operator, but the syntax itself is not esoteric.
The program is essentially equivalent to:
bool b;
int i;
sscanf(value, "%d", &i);
if (i != 0)
b = true;
else
b = false;
The key is that i != 0 is itself an expression that evaluates to true or false, not some magic that may only be used in an if statement.
Basically, if the condition (i not_equal_to 0 ) is satisfied, b gets the value "true". Else b gets the value "false".
Here, "i != 0" is a boolean expression that will be true if "i" is non-zero and false if it is zero.
All that is happening here is the result of that expression is being assigned to a variable.
You could also do things like...
boolean canDrinkAlcohol = (person.age() >= 18 && person.country.equals("UK") || person.age() >= 21 && person.county.equals("US"));
...
if(canDrinkAlcohol) {
...
}
or something
I have a sample midterm question that I am not too sure about. Here it is:
#include <iostream.h>
void f( int i )
{
if( i = 4 || i = 5 ) return;
cout << "hello world\n" ;
}
int main()
{
f( 3 );
f( 4 );
f( 5 );
return 0;
}
So I understand that the logical OR operator has a higher precedence and that it is read left to right. I also understand that what's being used is an assignment operator instead of the relational operator. I just dont get how to make sense of it all. The first thing the compiler would check would be 4 || i? How is that evaluated and what happens after that?
Let's add all the implied parentheses (remembering that || has higher precedence than = and that = is right-associative):
i = ((4 || i) = 5)
So, it first evaluates 4 || i, which evaluates to true (actually, it even ignores i, since 4 is true and || short-circuits). It then tries to assign 5 to this, which errors out.
As written, the code doesn't compile, since operator precedence means it's i = ((4 || i) = 5) or something, and you can't assign to a temporary value like (4 || i).
If the operations are supposed to be assignment = rather than comparison == for some reason, and the assignment expressions are supposed to be the operands of ||, then you'd need parentheses
(i = 4) || (i = 5)
As you say, the result of i=4 is 4 (or, more exactly, an lvalue referring to i, which now has the value 4). That's used in a boolean context, so it's converted to bool by comparing it with zero: zero would become false, and any other value becomes true.
Since the first operand of || is true, the second isn't evaluated, and the overall result is true. So i is left with the value 4, then the function returns. The program won't print anything, whatever values you pass to the function.
It would make rather more sense using comparison operations
i == 4 || i == 5
meaning the function would only print something when the argument is neither 4 nor 5; so it would just print once in your example, for f(3).
Note that <iostream.h> hasn't been a standard header for decades. You're being taught an obsolete version of the language, using some extremely dubious code. You should get yourself a good book and stop wasting time on this course.
The compiler shall isuue an error because expression 4 || i is not a lvalue and may not be assigned.
As for the expression itself then the value of it is always equal to true because 4 is not equal to zero.