Reputation: 1
Is a*=b;
the same as a*a=b;
, and if not, what is its equal?
I'm little confused because I keep getting wrong answer on this test:
#include<stdio.h>
main ()
{
int i, j, a=1, b=3;
for(j=1; j<3; j++)
a*=b;
b++;
printf("a=%d", a);
}
Upvotes: 0
Views: 90
Reputation: 33
First) You need to in-close the for loop with {}
int j;
for(j=1; j<3; j++){
printf("like this");
}
Second) a*=b is the same as a=a*b. a*a=b is trying to store the value of b in a variable called a*a.
int a*a;
int b;
a*a=b;
Which won't work because a*a isn't a valid variable name.
Lastly) The result of your code, how you have it written (once you fix the for loop with {}) should be:
a=3a=12
Upvotes: 0
Reputation: 70893
a *= b;
compiles.
a * a = b;
does not compile, giving something like this:
error: lvalue required as left operand of assignment
From the above we can conclude:
No, the both expressions are not equal
As the second expression above does not compile you either have no equivalent or endlessly.
For the first expression there are (at least) two equivalents:
a = a * b;
or
a = b * a
Upvotes: 0
Reputation: 9130
What is the "wrong" answer you're getting, and which one do you expect? Note that b++
is outside of the loop; use {
and }
to create a block for the loop's body if you want it executed within the loop
for(j=1; j<3; j++) {
a*=b;
b++;
}
Other than that, to answer your actual question: What Eoin said, and in this context take a look at what an lvalue and rvalue is.
Upvotes: 1
Reputation: 833
a *= b;
is equivalent to a = a * b;
.
*=
is a compound assignment operator - you can read more about them here: http://tigcc.ticalc.org/doc/opers.html#assign
There's also a good explanation of this and other operators here: http://www.tutorialspoint.com/ansi_c/c_operator_types.htm
Upvotes: 2