codescracker


c++

C++ Shorthand



« Previous Tutorial Next Tutorial »


C++ offers special shorthands that simplify the coding of a certain type of assignment statement. For example,

a = a + 10;

can be written as

a += 10;

The operator += tells the compiler to assign to a the value of a+10. This shorthand works for all the binary operations in C++ (those that require two operands). The general form of C++ shorthand is :

var = var operator expression ;

is same as

var operator = expression ;

Following are some examples of C++ shorthands :

x - = 10 ;		equivalent to		x = x - 10 ;
x ∗ = 3 ;		equivalent to		x = x ∗ 3 ;
x / = 2 ;		equivalent to		x = x/2 ;
x % = 2 ;		equivalent to		x = x % z ;

C++ Shorthand Example

Let's take an example, demonstrating shorthand concept in C++

/* C++ Shorthand */

#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();

	int x, res1, res2;

	x = 20;
	x = x - 10;
	res1 = x;
	x = 20;
	x -= 10;
	res2 = x;
	cout<<res1<<"\t"<<res2<<endl;

	x = 20;
	x = x * 3;
	res1 = x;
	x = 20;
	x *= 3;
	res2 = x;
	cout<<res1<<"\t"<<res2<<endl;

	x = 20;
	x = x/2;
	res1 = x;
	x = 20;
	x /= 2;
	res2 = x;
	cout<<res1<<"\t"<<res2<<endl;

	x = 20;
	x = x % 2;
	res1 = x;
	x = 20;
	x %= 2;
	res2 = x;
	cout<<res1<<"\t"<<res2<<endl;

	getch();
}

Here is the sample output of the above C++ program:

c++ shorthand

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test