Welcome to pickSourcecode.com Login | Register    
pickZy.com
 Home  | search  | games  | General  | C  | C++  | Java  | Php  | Networking  | Visual Basic  | VC++  | Win32  | MFC  | JavaScript  | Jobs  | JavaScript  | Post jobs
C - Assignment operators and expressions       Share
2007-08-30 |  RatheeshTR  | Viewed: 442  |    0


Assignment Operators and Expressions:


Expressions such as

             i  =  i + 2;

in which the variable on the left hand side is repeated immediately on the right can be written in the compressed form.

            i    +=   2

The operator +- is called an assignment operator.

we don't ``evaluate'' the i on the left hand side of the = at all, we assign to it. The distinction becomes important, however, when the left hand side (expr<sub>1</sub>) is more complicated than a simple variable. For example, we could add 2 to each of the n cells of an array a with code like

	int i = 0;
while(i < n)
a[i++] += 2;
If we tried to use the expanded form, we'd get
	int i = 0;
while(i < n)
a[i++] = a[i++] + 2;
and by trying to increment i twice within the same expression we'd get (as we'll see) undesired, unpredictable, and in fact undefined results. (Of course, a more natural form of this loop would be
	for(i = 0; i < n; i++)
a[i] += 2;
and with the increment of i moved out of the array subscript, it wouldn't matter so much whether we used a[i] += 2 or a[i] = a[i] + 2.)

Most binary operators (operators like + that have a left and right operand ) have a corresponding assignment operator op =, where  op is one of

+     -      *     /       %      <<       >>      &     ^     |


If expr1 and expr2  are expressions, then 

     expr1  op =   expr2


eg,
int bitcount (unsigned x)
{
        
  int   b;
        
  for ( b=0;  x !=  0;  x>>=1)
             
   if ( x &  01)
                     b++;
         
           return b;
}


Latest topics
C - Arrays of structures  Viewed: 285
C - structures and functions  Viewed: 292
tcpdump by host name or ip  Viewed: 292
C - pointers and Arrays  Viewed: 295
C - File Access  Viewed: 295
C - For loop statements  Viewed: 296
C - pointers to pointers  Viewed: 296
C - Register variables  Viewed: 297
C - Static variables  Viewed: 299
C - Pass-by-reference parameters  Viewed: 300

Comments:





Submit comment's

Type:

User Comment's:

Submitted By:
Prof: Software Engineer
Tech: C ,Cpp
Send Mail: ratheesh



Related topics
C - Functions and program structure, Programmed pass-by-reference via pointers, Pass-by-reference parameters
C - Pass-by-reference parameters
C - pass-by-reference via pointers

Related References
c - swap num, pass-by-reference parameters
c - pass-by-reference via pointers

Web site contents © Copyright 2007, All rights reserved.
Help | Terms and Conditions | Privacy Policy | About Us