0

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);
    }
Jens
  • 8,423
  • 9
  • 58
  • 78

5 Answers5

2

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

Eoin
  • 833
  • 2
  • 13
  • 24
1

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.

Community
  • 1
  • 1
Jens
  • 8,423
  • 9
  • 58
  • 78
0

a*=b is equivalent to a = a*b.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0
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
alk
  • 69,737
  • 10
  • 105
  • 255
0

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
Ulrick
  • 33
  • 7