Skip to content

Instantly share code, notes, and snippets.

@hchasens
Last active July 5, 2023 03:40
Show Gist options
  • Save hchasens/52ba6c1f0c6ccadfbb45cc0978e960de to your computer and use it in GitHub Desktop.
Save hchasens/52ba6c1f0c6ccadfbb45cc0978e960de to your computer and use it in GitHub Desktop.
C one-line macro that finds the length of an int `x`. [E.g. lenOfInt(12345) will return 5]
/**
* Needs <math.h> to work as it calls the ceil() function.
* Doesn't work on neg ints without modification [see line x for example]
* Returns a short to reduce spatial complexity; modify to cast as int if needed.
*
**/
#include <stdlib.h>
#include <math.h>
#define lenOfInt(x) ((x) == 0 ? 1 : (int)(log10(abs(x)) + 1))
// example code driver
#include <stdio.h>
int main()
{
printf("%d\n", lenOfInt(9334));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment