In this tutorial, we will be discussing a program to understand how to sum two integers without using arithmetic operators in C/C++.
For adding two integers without using arithmetic operators, we can do this with either using pointers or using bitwise operators.
Example
Using pointers
#include <iostream> using namespace std; int sum(int a, int b){ int *p = &a; return (int)&p[b]; } int main() { int add = sum(2,3); cout << add << endl; return 0; }
Output
5
Example
Using bitwise operators
#include <iostream> using namespace std; int sum(int a, int b){ int s = a ^ b; int carry = a & b; if (carry == 0) return s; else return sum(s, carry << 1); } int main() { int add = sum(2,3); cout << add << endl; return 0; }
Output
5