Last active
June 10, 2020 02:18
-
-
Save nyrahul/f95d664a8f7f4e153603d27ab020cff7 to your computer and use it in GitHub Desktop.
cpu efficient c one-liners
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool isPowOf2(val) | |
{ | |
return val && !( val & ( val - 1)); | |
// val && is required so that val=0 is handled. 0 is not the pow of 2 | |
} | |
/* increment val only if MAX_UINT val not reached. Use-case: for stats incr, you dont want the val to cycle */ | |
#define STAT(S) (S) += (!!(S ^ 0xffffffff)) // S will incr by 1 only till it reach 0xffffffff | |
/* Set flag if C is non-zero, Reset flag in val if C is zero */ | |
#define SET_FLAG_IF(VAL, FLAG, C) \ | |
(VAL) &= ~(FLAG); /* Reset the flag */ \ | |
(VAL) |= -!!(C) & (FLAG); /* Set the flag if C is non-zero */ | |
/* Count Macro arguments */ | |
#define _GET_NTH_ARG(_1, _2, _3, _4, _5, N, ...) N | |
#define CNT(...) _GET_NTH_ARG("ignore", ##__VA_ARGS__, 4, 3, 2, 1, 0) | |
int main() | |
{ | |
printf("one arg: %d\n", CNT()); // outputs 0 | |
printf("one arg: %d\n", CNT(1)); // outputs 1 | |
printf("three args: %d\n", CNT(1, 2, 3)); // outputs 3 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment