How to convert C to C++? - c++

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.

Related

Why adding "variable + 1" doesn't increment its value by one for every loop in a for loop? (C++)

I'm having a hard time understanding why using a increment operator in a for loop in C++ has a different result than doing 'variable' + 1. The variable in the second case simply isn't remembered after each iteration of the loop:
Take the following code:
#include <iostream>
int main(){
int a{0};
for (int i = 0; i < 5; i++){
std::cout << ++a;
}
return 0;
}
It outputs as expected:
12345
However, if I instead replace ++a with a + 1:
#include <iostream>
int main(){
int a{0};
for (int i = 0; i < 5; i++){
std::cout << a + 1;
}
return 0;
}
I get:
11111
Even if I make the 'a' variable static:
static int a{0};
It still outputs 11111.
Why doesn't 'a + 1' preserve its value after every loop? What would I need to do if I wanted to preserve its value after every iteration without using ++ (for instance, with another operation like a * 2)?
Why doesn't 'a + 1' preserve its value after every loop?
a + 1 is an expression that doesn't assign anything to a. That is a is not affected in any way. This means when you do just a + 1, the value of a is still 0(the old value).
On the other hand ++a has the same effect as:
v---------->assignment done here implicitly
a = a+1
In the above expression ++a, the value of is incremented by 1 so that the new value of a is now 1.
++a is equivalent to the assignment a= a + 1 (or a+= 1). The expression a + 1 alone does not modify a.
C++ will allow you to write std::cout << (a= a + 1);.
a++ is not the same thing as a+1 but as a=a+1.
What's the difference?
Well:
a+1 contains the value, which is one higher than the value of a.
a=a+1 means that, in top of this, this value gets assigned to the variable a, which means something like "replace a by its value plus one".
This gives following possibilities (I also show the difference between a++ and ++a):
int a=3;
cout<<a+1; // output : 4. Value of 'a' equals 3.
cout<<a+1; // output : 4. Value of 'a' equals 3.
cout<<a+1; // output : 4. Value of 'a' equals 3.
int a=3;
cout<<a++; // output : 3. Value of 'a' becomes 4 after having shown it on screen.
cout<<a++; // output : 4. Value of 'a' becomes 5 after having shown it on screen.
cout<<a++; // output : 5. Value of 'a' becomes 6 after having shown it on screen.
int a=3;
cout<<++a; // output : 4. Value of 'a' becomes 4 before showning it on screen.
cout<<++a; // output : 5. Value of 'a' becomes 5 before showning it on screen.
cout<<++a; // output : 6. Value of 'a' becomes 6 before showning it on screen.
Conceptually, the built-in arithmetic operators like + and * evaluate their operands, perform the respective operation with the thusly obtained values, and create a temporary object that contains the result.
The operands, one of which is your a, are only read from, not written to. That is more obvious when you consider that + is commutative, that is, its operands can be swapped without affecting the result: a+1 is by definition the same as 1+a, and clearly you cannot write anything back to the immediate value 1.
Generally, as you certainly know, = is used in C and C++ to write a value to a variable. C, and by means of ancestry also C++, provide shortcuts to write back the result of certain operations to one of their operands: it's the combination of the operator and the assignment =, for example a += 1. Like all assignments, this one is an expression (that is, it has a value) which has the value of the variable after the operation and assignment. Like all other expressions, you can use it as a subexpression, even though that's not very common: cout << (a += 1); would achieve the desired effect (the parentheses are necessary because assignment has about the lowest operator precedence). Because incrementing (and decrementing) by one is so very common, C and C++ have a shortcut for the shortcut: ++a is the same as a+=1, so that one would typically write cout << ++a; (as a side effect obviating the need for parentheses).

Compound Assignment (Multiply)

I recently learn the basic of C++. And i found something that i didn't get the idea. Here is the program that make me a little confuse.
#include <iostream>
using namespace std;
int main()
{
int m = 4, n;
n=++m*--m;
cout <<"m="<<m<<" and n="<<n<<"\n;
return 0;
}
And the output is m=4 and n=16.
I thought that
m=4, so ++m is 5, and --m will be 4,
then n= 5*4= 20.
Hence, the m=4 and n=20.
I think mine is false. So i need a help. Thank you.
The operands of * are unsequenced relative to each other. This means that not only may they be evaluated in any order; but if each operand contains multiple sub-steps, the sub-steps of one operand might be interleaved with those of the other operand.
An example of this might be (f() + g()) * (h() + i()) . The four functions could be called in any order -- it is not required that f and g are called together, etc.
Back to your example, the following two sub-steps are unsequenced relative to each other:
writing the new value to m, as part of ++m
reading m, as part of --m
When there are two unsequenced operations on the same variable (and at least one of them is a write), it is undefined behaviour which means anything can happen (including unexpected results).
This:
n=++m*--m;
is bad code. Replace it with something clear, such as:
n = (m + 1) * (m - 1);
The original code, for complicated reasons, may not do what you expect, so it's better not to write such code in the first place. If you want to know more about the nitty gritty details of why this is, see here: Undefined behavior and sequence points
++m means "increment m then use its value" The current call with have (m + 1) as value.
m-- means "use the value of m, then decrement it" The current call with have the original value of m, and subsequent calls will have (m - 1) as value
If that makes it any clearer for you, you can also rewrite it as:
int m = 4, n;
n = (m = (m + 1)) * (m = (m - 1));
I am pretty positive the operation occurs before the increment. That is why that is happening. If you break it down like this, it should work.
The answer should be 15 because 4 + 1 is 5 and 4 - 3 is 3, thus 5 * 3 is 15. See below
int main()
{
int m = 4, n;
int g;
n = (m+1) * (m-1);
std::cout << "m=" << m << " and n=" << n << "\n" ;
std::cin >> g;
return 0;
}

C++ Error "lvalue required as left operand of assignment"

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.

Operator Precedence

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.

Bizarre condition syntax

I came across the following for loop with a very unusual condition
int main( int argc, const char* argv[] ) {
for ( int i = 0 ; i < ( 10, 20 ) ; i++ ) {
cout << i << endl;
}
}
This source code compiled successfully. It executed the loop with i with values from 0 to 19 (the 10 in the expression (10, 20) seems to have no effect on the number of iterations).
My question:
What is this condition syntax? Why doesn't it cause a compile error?
EDIT:
The bigger picture: this questions started with a bug, the original condition was supposed to be i < std::min( <expr A>, <expr B> ) and for some reason I omitted the std::min.
So, I was wondering why the code compiled in the first place. Now I see the bug is a legit (albeit useless) syntax.
Thanks!
It is the comma operator. It evaluates both sides of the expression, and returns the right one.
So, expression (10, 20) does nothing, but returns '20'.
See also
Uses of C comma operator.
http://en.wikipedia.org/wiki/Comma_operator
(10, 20) means evaluate the integer 10, then evaluate 20, then return 20 (the rightmost). So it just means 20.
The comma operator is often useful in for loops, as it allows things such as x = 0, y = 1 (i.e. two assignments in one expression), but here it's useless.
, operator in c++ work as a binary operator which checks first value, discard it and return the next value. In short.
for(int i=0;i<(10,20);i++) will be equal to for(int i=0;i<20;i++)