A !Quick Lesson in Operators

Operators are one of the core components of any programming language. Knowing how they are classified and how they can be used is extremely important. This post might teach you some new operators. Since the samples are pulled from multiple languages, you may even learn something cool about a new language. Enjoy, and please point out any mistakes.

Arithmetic operators

Ok, lets roll through these as fast as we can. You know these, right?

+ for addition
- for subtraction
* for multiplication
/ for division
% for modulo (remainder after two numbers have been divided)

You can use each of these operators to work with numeric data types (examples in C – int, float, and double are all numeric data types):

//Addition
int x = 2 + 2; //4
int x = 2.0 + 2; //4;
float x = 2.0 + 2; //4.000000

//Subtraction
int x = 2 - 2; //0;
double x = 2.0 - 42; //-40

//Multiplication
int x = 2 * 2; //4

//Division
int x = 3 / 2; //1
double x = 3.0 / 2; //1.5
double x = 3 / 2; //1.000000 <- Be careful with these!

//Modulo
int x = 5 % 4; //1
double x = 3.0 % 2; //Won't compile, actual sanity check here!

Relational (also called comparison) operators

These operators are used to compare values. In all languages they can compare numeric types. In most languages they can compare strings and characters as well as simple datatypes (such as enums). In some languages they can compare more complex data types such as vectors, arrays, and objects.

>= greater than or equal to
> greater than
<> not equal to (less than OR greater than)
<= less than or equal to
< less than
!= not equal to
== equal to
=== equal and same type (PHP)

Python:

3 >= 4 #False
4 > 3 #True
"test" <> "test" #False
"apple" != "orange" #True
"3" == "3" #True

PHP:

$arr = array();
$arr2 = array();
var_dump($arr == $arr2); // bool(true)

$obj = new StdClass;
$obj2 = new StdClass;
$obj->apple = 'test';
var_dump($obj == $obj2); //bool(false)

var_dump(3 === "3") //bool(false)

Logical operators

&& and
|| or
! not

Increment and decrement operators

Pretty simple, like the arithmetic operators…

++var //Increment, equal to var + 1
–var //Decrement, equal to var – 1
+= //Add one number to another
-= //Subtract one number to another

var i = 1;
++i; //2
--i; //1
i += 1; //2
i -= 1; //1

Assignment operators

= //Assign a value
+= //Compact assignment, addition, equal to x = x + y
-= //Compact assignment, subtraction, equal to x = x – y
*= //Compact assignment, multiplication, equal to x = x * y
/= //Compact assignment, division, equal to x = x / y
%= //Compact assignment, modulo, equal to x = x % y

Bitwise operators

& //True if any is true. Evaluates to last statement (meaning all conditions are checked).
| //True if either is true.
^ //True if only one is true.
<< and >> // Left shift / right shift operators. Perform shifts at binary level.

Note that & and && are different in that && “short circuits” if one of the conditions it’s evaluating or false. ┬áConsider the following example:

#include "stdio.h"

int printSomething()
{
	printf("%s", "Something");
	return 1;
}

int main()
{
	int x = 3, y = 2;

	int a = (x > y & y > 5 & printSomething()); //"Something" is printed

	int b = (x > y && y > 5 && printSomething()); //"Something" is not printed.  && operator short circuits and after y > 5 evaluates to false conditions stop being evaluated.

	printf("Example 1: %d \n \n", a);

	printf("Example 2: %d \n \n", b);

	return 0;
}

The | operator is the same as the &, but does OR comparisons.

The ^ operator evaluates whether or not ONLY ONE of the conditions is true:

#include "stdio.h"

int main()
{
	int x = 1, y = 2, z = 3;

	if(y > z ^ x > y ^ x > 0) printf("%s \n \n", "True!"); //Only one condition is true, statement evaluates to boolean true

	if(z > y ^ x > 0) printf("%s \n \n", "Also True!"); //Both conditions are true.  Statement evaluates to boolean false and "Also True!" is not printed

	return 0;
}

Shift operators work at the binary level. Easy way to raise any multiple of 2 to the nth power:

#include "stdio.h"

int main()
{
	int x, z, y = 2, a = 3, r;

	x = y << 2;  //Binary operation.  Bits are shifted two places to the left (001 becomes 100).  This evalutes to 8

	printf("%d \n \n", x);

	z = a << 2;  //Binary operation.  a starts as 011 and bits are shifted two spaces to the left.  a becomes 1100 (12)

	printf("%d \n \n", z);

	r = z >> 2;  //Binary operation.  r shifts z to spaces right.  r is 3.

	printf("%d \n \n", r);
}

Ternary

Seeing this freaked me out when I first started programming, but it’s actually really easy.

#include "stdio.h"

int main()
{
	int x = 1, y = 2, a;

	a = (x > y) ? x : y; //IF x > y, a = x, ELSE, a = y

	printf("%d \n \n", a); //a is equal to y
}

Other operator uses (strings, arrays, objects, etc.)

. //Dot notation for concatenating strings, not to be confused with dot notation like calling a method in ruby or python
+ //Used for concatenating strings. In some languages more complex data types can be joined.
+= //Add one string to another
.= //Concatenate strings
&= //Reference assignment

PHP

$string = 'test';
$stringtwo = 'test2';
$concat = $string . '  ' . $stringtwo; // "test test2"

$concatTwo = '';
$concatTwo .= $string;
$concatTwo .= $stringtwo; //test test2

$ref &= $string; //"test"

JavaScript

var myString = 'test';
var mySecondString = 'test2';

var concat = myString + mySecondString; //value is testtest2

Python uses the same concept:

test = "test"
maybe = "tester"

test + maybe # 'testtester'

In PHP associative arrays can be joined with the + operator. It’s not a good idea to add arrays with numeric keys because only one value will be retained:

$one = array('test');
$two = array('test2');

$three = $one + $two; //$three is now array('test');

$four = array('test' => 'tester');
$five = array('tester=> 'tester2');

$six = $one + $two; //$six is array('test' => 'tester', 'tester' => 'tester2');

At least in the languages I know a bit about, the -. *, % and / operators cannot be used on any non-integer types.

That’s all I got. Hope you learned something!

This entry was posted in Programming. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. sushant
    Posted March 2, 2012 at 10:21 pm | Permalink

    int x=3/2;
    double x=5%4;
    will int x be equal to double x

  2. Calvin Froedge
    Posted March 2, 2012 at 10:31 pm | Permalink

    Yes, int x=3/2 would appear to be equivalent to double x=5%4 if, for example, you ran them in the python interpreter. You’ll get 1 for both.

    However, do int x = 3./2 ….You’ll get 1.5.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>