24
printf/scanf and return value
C Language
Basic

We know that printf and scanf functions are used to print a value and scan a value respectively but most of the people don't know the return values of them.

For example:

int main() {
int n;
printf("%d",scanf("%d",&n));
return 0;
}

Then what will be output?

output:  1

Because scanf will return the total number of input successfully scan. This will more clear when we will take another example

int main() {
int n;
printf("%d",scanf("%d %d",&n,&n));
return 0;
}

Output:  2

Printf function returns total number of characters printed

int main() {
int n;
printf("%d",printf("%d",100));
return 0;
}

Output: 3

Because 100 has 3 char '1' '0' '0'

Now we can think in another way like

    int main() {    
    int n=4;    
    printf("scanf("%d %d",&n,&n)");    
    return 0;
}

what will be the output in this case? It will be an error because it breaks the printf rule %d %d are out of double quotes, first quotes have "scanf(" and second have ",&n,&n"

But if we will do it in some other manner like below

int main() {
    int n=4;    
    printf("scanf(\"%d %d\",&n,&n)");   
    return 0;    
}

then it will not give any error it will print scanf(\"GARBAGE -VALUE1 GARBAGE- VALUE2 \",&n,&n) Because in printf we have not assigned any value to %d so it will printf any random value (GARBAGE VALUE) It will be more clear with this

int main() {        
    int n=4;        
       printf("scanf(\"%d %d\",&n,&n)",5,6);        
       return 0;
}

It will print

scanf("5 6",&n,&n)

Hope you enjoy it!

Rohit Kumar

Author

Notifications

?