Add two numbers without using arithmetic operators

Problem Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc). Solution We can get carry by &(and) operator and bit by ^ (xor) operator. We have already seen, how we can use bit-wise operators to replace arithmetic operators i.e. implement arithmetic operators using bitwise operators. Method 1 - Iterative method int Add(int x, int y) { // Iterate till there is no carry while (y ! [Read More]

Implement Add,Subtract,Multiplication,Division Using Bit Manipulation

Addition This One is Somewhat Logical and the Best also. This will work all kind of Inputs. The Logic Behind the Concept is described breifly here : Here we use, One’s Complement Operator (~ - Known as Tilda). This is a Unary Operator. The output of “~b” means, One Complement of the value stored in ‘b’. For example, a=10, b=5. Then the ~b=-6. This operator simply works on the binary value of the corresponding Integer. [Read More]

Using == operator in better way in cpp

In cpp, it is possible that instead of
i==5

we can do

i=5

So we assign i = 5 and if it is like
if(cond)
cond gets true.

So better is
5==i
beause == is symmetric.
If someone writes by mistake is
5=i
As we get error = ‘can’t assign value to literal’.

sizeof operator

**1)** Why is sizeof operator and not function sizeof() is a compile time operator. To calculate the size of an object, we need the type information. This type information is available only at compile time. At the end of the compilation phase, the resulting object code doesn’t have (or not required to have) the type information. Of course, type information can be stored to access it at run-time, but this results in bigger object code and less performance. [Read More]

Pointer indirection with care

* and . operator struct rec { int i; float f; char c; }; int main() { struct rec \*p; p=(struct rec \*) malloc (sizeof(struct rec)); (\*p).i=10; } To initialise pointer to 10, we have to use parentheses, because . operator has higher precedence than * operator. ++ and * Consider **\*p++** The postfix “++” operator has higher precedence than prefix “*” operator. Thus, *p++ is same as *(p++); it increments the pointer p, and returns the value which p pointed to before p was incremented. [Read More]

Operator Precedence in C & CPP

Operator Precedence Chart Operator Type Operator Associativity 1. Primary Expression Operators () [] . -> expr++ expr– left-to-right 2. Unary Operators * & + - ! ~ ++expr –expr right-to-left (typecast) sizeof() 3. Binary Operators * / % left-to-right + - » « < > <= >= == != & ^ | && || 4. Ternary Operator ?: right-to-left 5. Assignment Operators = += -= *= /= %= »= right-to-left [Read More]