Showing posts with label Assignments. Show all posts
Showing posts with label Assignments. Show all posts

Thursday, September 30, 2010

Structure Assignments in C,C++

The information contained in one structure may be assigned to another structure of the
same type using a single assignment statement. That is, you do not need to assign the
value of each member separately. The following program illustrates structure
assignments:
#include <stdio.h>
int main(void)
 {
struct {
int a;
int b;
} x, y;
x.a = 10;
y = x; /* assign one structure to another */
printf("%d", y.a);
return 0;
}
After the assignment, y.a will contain the value 10.

Sunday, September 26, 2010

Pointer Assignments in C,C++

As with any variable, you may use a pointer on the right-hand side of an assignment
statement to assign its value to another pointer. For example,
#include <stdio.h>
int main(void)
{
int x;
int *p1, *p2;
p1 = &x;
p2 = p1;
printf(" %p", p2); /* print the address of x, not x's value! */
return 0;
}
Both p1 and p2 now point to x. The address of x is displayed by using the %p printf()
format specifier, which causes printf() to display an address in the format used by the
host computer.

Tuesday, September 21, 2010

Shorthand Assignments

There is a variation on the assignment statement, sometimes referred to as a shorthand
assignment, that simplifies the coding of a certain type of assignment operation. For
example,
x = x+10;
can be written as
x += 10;
The operator += tells the compiler to assign to x the value of x plus 10.
This shorthand works for all the binary operators (those that require two
operands). In general, statements like:
var = var operator expression
can be rewritten as
var operator = expression
For another example,
x = x-100;
is the same as
x -= 100;
Shorthand notation is widely used in professionally written C/C++ programs; you
should become familiar with it.