-2

As the title says I am a bit confused by what <<= represents. I know << is a shift operator, but this is the first time I saw a = along with it. Any clarifications?

Sample code:

#include <stdio.h> 
main() { 
  unsigned int i, s; 
  for( s = i = 0; i <= 7; i++){ 
    switch (i%3) { 
      case 0: i++; 
      case 1: i <<= (7 & (i + 1)) | ((i + 2) & 6); s += i; break; 
      case 2: i += (i ^ i) | 1 ; continue; 
    } 
    s++; 
  } 
  printf("%d\n", s); 
} 
nalply
  • 26,770
  • 15
  • 78
  • 101
murtaugh
  • 77
  • 8
  • 8
    That's simple: `a <<= 7` equal to `a = a << 7`. – Eddy_Em Apr 21 '13 at 10:36
  • Similar to `+=`. But replace `+` with `<<`. – Azmi Kamis Apr 21 '13 at 10:37
  • Thanks! Post it as an answer? :) – murtaugh Apr 21 '13 at 10:37
  • 2
    2 downvotes (and counting) for a newbie like me asking a question that he didn't know the answer to and searched the net before posting. What is this site about again? :/ – murtaugh Apr 21 '13 at 10:53
  • @murtaugh This site expects that you have read a basic C book end-to-end on your own.It should be obvious to anyone who has the least idea about the level of questions asked on StackOverflow.So purrlease, do away with your sarcasm.What you asked is TOO basic and shows you haven't done your homework first. – Rüppell's Vulture Apr 21 '13 at 10:58
  • 1
    See also: http://stackoverflow.com/q/2505550/220060 (it's not a duplicate because it's a different language, but C and C# are very similar in this aspect). – nalply Apr 21 '13 at 13:50
  • 2
    @SheerFish: This is a good question. There are many similar questions on SO like this one: http://stackoverflow.com/q/2462946/220060. – nalply Apr 21 '13 at 16:54

3 Answers3

8

AFAIK >>= is the "same" operation. you can either call

i = i << 4;

or

i <<= 4;

It has the same effect.

It's like i = i + 5; and i += 5;

manuels
  • 1,511
  • 3
  • 14
  • 26
3

This operator is called the Bitwise Left Shift Assignment operator.

C and languages in the C family (C++, Java, Objective C, C# and others) have something called compound assignment operators. They have this general form:

a OP= b;

where OP is one of the many allowed operators like

  • + addition giving +=
  • - subtraction giving -=
  • * multiplication giving *=
  • / division giving /=
  • | bitwise or giving |=
  • & bitwise and giving &=

only to name a few.

And what do the compound assignment operators do??

They are a shorthand. Instead of

a = a OP b;

use

a OP= b;

There is a second benefit. a is evaluated only once.

This is an advanced concept. For more details see this StackOverflow answer for Left side evaluated only once.

Community
  • 1
  • 1
nalply
  • 26,770
  • 15
  • 78
  • 101
0

<<= Shift the value of the first operand left the number of bits specified by the value of the second operand; store the result in the object specified by the first operand.

JSON C11
  • 11,272
  • 7
  • 78
  • 65