0

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.

Ajai
  • 3,440
  • 5
  • 28
  • 41
  • 1
    It works, but it's inefficient and it generates spurious output on stdout. – Paul R Oct 21 '11 at 10:15
  • 1
    To return the length of the printed representation of the value of the variable. Also printf has a side effect: it prints things :) So it is not as clean as a function without side effet to compute the length. – Ludovic Kuty Oct 21 '11 at 10:15
  • @LudovicKuty: Agreed. But lets say that I have a function that prints the variable for which it needs to find the length. I prints the variable and its length which I am doing in my snippet above. So in this case writing a clean code is still in question? – Ajai Oct 21 '11 at 10:25
  • @PaulR: Why does the output have to be spurious? Can you please give me an example? – Ajai Oct 21 '11 at 10:26
  • @Ajai: you get spurious output because printf has a side effect, i.e. it generates output on stdout - so for every variable you want to evaluate you'll be `printf`ing that variable on stdout. – Paul R Oct 21 '11 at 10:36
  • @Ajai If you forget the fact that printf has to make extra work to do its thing and that it has a side effect, then why not. – Ludovic Kuty Oct 21 '11 at 12:42

2 Answers2

3

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 sizeof and strlen functions) 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:

float num = 10.0f;
printf("%.10f", num); // return value should be 13
printf("%f", num);    // return value depends on the implementation of printf and the float value supplied

Also you have to consider that there are other representations than the decimal one.

As others have already stated, printf has the side effect that it actually writes to stdout. If you do not want this, you can use snprintf to write to a buffer and not to stdout:

char buffer[256];
int x = 10;
snprintf(buffer, sizeof(buffer), "%d", x); // return value is '2'
Constantinius
  • 34,183
  • 8
  • 77
  • 85
0

"One liner to find length of a variable"

Not possible unless its builtin to your compiler, or you define a wild and hairy macro half a page long with a few enums to state your type...

For strings, (which you cannot use sizeof on...) see: https://stackoverflow.com/a/22128415/3370790

Community
  • 1
  • 1