Builtin functions of GCC compiler in C++


In the GCC compiler there are some builtin functions. These functions are like below.

Function _builtin_popcount(x)

This builtin function is used to count the number of 1s in an integer type data. Let us see an example of _builtin_popcount() function.

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   int n = 13; //The binary is 1101
   cout << "Count of 1s in binary of "<< n <<" is " << __builtin_popcount(n);
   return 0;
}

Output

Count of 1s in binary of 13 is 3

Function _builtin_parity(x)

This builtin function is used to check the parity of a number. If the number has odd parity, it will return true, otherwise it will return false. Let us see an example of _builtin_parity() function.

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   int n = 13; //The binary is 1101
   cout << "Parity of "<< n <<" is " << __builtin_parity(n);
   return 0;
}

Output

Parity of 13 is 1

Function _builtin_clz(x)

This builtin function is used to count the leading zeros of an integer. The clz stands for Count Leading Zeros. Let us see an example of _builtin_clz() function.

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   int n = 13; //The binary is 1101
   //0000 0000 0000 0000 0000 0000 0000 1101 (32bit integer )
   cout << "Leading zero count of "<< n <<" is " << __builtin_clz(n);
   return 0;
}

Output

Leading zero count of 13 is 28

Function _builtin_ctz(x)

This builtin function is used to count the trailing zeros of an integer. The ctz stands for Count Trailing Zeros. Let us see an example of _builtin_ctz() function.

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   int n = 12; //The binary is 1100
   //0000 0000 0000 0000 0000 0000 0000 1100 (32bit integer )
   cout << "Trailing zero count of "<< n <<" is " << __builtin_ctz(n);
   return 0;
}

Output

Trailing zero count of 12 is 2

Updated on: 30-Jul-2019

396 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements