I just stumbled upon the idea that since printf returns the no.of characters it has printed to the output stream why not use it to find length of any variable in c?
The code goes something like this,
#include<stdio.h>
int main()
{
char *a="Length";
int i=1000;
printf("Size: %d\n",printf("%d\n",i)-1);
printf("String Size: %d",printf("%s\n",a)-1);
return 1;
}
Am I right? I am not concerned about where it is being used. just wanted to know if my understanding is right.
What do you mean by “length of any variable”? You mean the number of bytes used to store the variable (which better achieved with the
sizeofandstrlenfunctions) or the byte length of the string representation of the variables?For the latter one, you should be careful, since you can use format options to actually modify the results. Consider the following example:
Also you have to consider that there are other representations than the decimal one.
As others have already stated,
printfhas the side effect that it actually writes tostdout. If you do not want this, you can usesnprintfto write to a buffer and not tostdout: