Set a specific bit to a specific value This is the code I came up with: 

void set_bit_at_pos(int* num, int pos, bool val)
{
    if (val) {
        int mask = 1 &lt;&lt; pos;
        *num |= mask;
    }
    else {
        int mask = ~(1 &lt;&lt; pos);
        *num &amp;= mask;
    }
}


I'm new to bitwise operations, so this approach may not be the best. Nevertheless any suggestions are appreciated.

For the following main: 

int main()
{
    int num = 5;
    cout &lt;&lt; num &lt;&lt; endl;
    set_bit_at_pos(&amp;num, 1, true);
    cout &lt;&lt; num &lt;&lt; endl;
}


(I know about using namespace std;) 

This is the output:

5
7
This is simpler:

#include &lt;stdint.h&gt; // #include &lt;cstdint&gt; in C++

void write_bit_32b(uint32_t *num, uint8_t pos, bool val)
{

        *num &amp;= ~(UINT32_C(1) &lt;&lt; pos);
        *num |= (uint32_t)val &lt;&lt; pos;
}




Use fixed-width integers if you can (see above).



Use int main(void):

C17::6.11.6: 


  Function declarators The use of function declarators with empty
  parentheses (not prototype-format parameter type declarators) is an
  obsolescent feature.




This may be interesting to you:

https://stackoverflow.com/q/47981/6872717