For loop with printf as arguments - c

I can't understand why the following code outputs 10.
What I understand is that !printf("0") means !0, which is TRUE. So why doesn't the code print "Sachin"
#include <stdio.h>
int main() {
for (printf("1"); !printf("0"); printf("2"))
printf("Sachin");
return 0;
}
Output
10

let's analyze this side-effect loop statement:
for(printf("1"); !printf("0"); printf("2"))
The first statement is executed, always (init condition), yieiding 1
Then the condition is tested: !printf("0") prints 0, then since printf returns 1 because it just prints 1 character, the negation returns 0 and the loop is never entered because the condition is false right from the start. So neither 2 or Sachin are printed.
Of course, this code isn't practical, almost unreadable. So don't ever do things like this (puts("10"); is a good alternative for instance).
more on the return value of printf (that is often ignored):
Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).
(from https://linux.die.net/man/3/printf)

If you look at the man printf reference on google, you'll see that this function returns the number of written bytes.
Here your condition is !printf("0"), in other words : "as long as the return of printf is not existing (or equal 0), do something. But you print the character '0' so printf actually return 1 so your condition is false.
Now WHY it prints 10 :
The first printf("1") prints 1.
Your condition is tested at least once, so the second printf("0") occurs one time (it prints 0)

printf("1")
prints 1 and it return number of characters which is 1
printf("0")
prints 0 and it return number of characters which is 1
!1 means !(true) = false so execution will stop and you will see 10 as output.

Related

c - Last call to function is being printed again

This is the loop in my a4.c main method that calls the patternsearch function:
while(!feof(stdin)) {
scanf("%s", &word);
patternSearch(grid, word);
}
For some reason that I can't figure out, this prints the last call to patternsearch twice:
For example, look at my output for test3:
Found "tip" at 0 2, L
Found "pop" at 0 0, D
Found "pop" at 2 0, U
Found "key" at 0 3, D
Found "key" at 2 1, R
"nope" - Not Found
"nope" - Not Found
As you can see, the test result for 'nope' was printed twice. :(
I think my problem is similar to the one stated here:
Last line being printed twice (C++)
but I'm not sure.
Step 1 with any problem involving input: test the return value from the input function.
feof() checks if a prior read resulted in an end-of-file. It does not report about future reads.
Code is having trouble with unexpected results of scanf("%s", &word);, yet code did not check the return value from scanf(). Weak code does not check the return value. Robust code does. Research the proper use of scanf() and its return values.
Do not use "%s" without a width limit.
The & in scanf("%s", &word); is likely not needed. Would need to see word declaration to be sure.
char word[100];
while (scanf("%99s", word) == 1) {
patternSearch(grid, word);
}
The issue here was that feof() only returned true when I actually hit the EOF character.
That means that I was calling scanf(), and hitting the EOF;
that means the loop won't iterate again, but I was already in the middle of it.
But scanf() only actually changes the argument I hand it if it successfully reads what I asked;
since it failed (by hitting EOF),
it won't change the character array, which will still contain whatever it did before (i.e. the previous word).
I checked the return value of scanf(); the number it returns, which is the number of arguments it put a new value into;
if that's less than 1, then I didn't actually get a new string (I think it also explicitly returns EOF if it hits the end-of-file; EOF is a #defined constant that's equal to -1 on most platforms, so the <1 check will work anyway).
This is the code that finally worked:
while(!feof(stdin)) {
if (scanf("%s", &word) < 1)
break;
patternSearch(grid, word);
}

why the result of '*s-*t" in the while loop is "67"?

please i can't understand the while loop , why the loop show A two time and not one
char *s,*t;
s="ABC";
t="AA";
do {printf("A");}
while(*s++==*t++);
printf("%d %d",*s-*t);
In your code
printf("%d %d",*s-*t);
invokes undefined behavior as you're not supplying enough argument to sate the supplied format specifiers.
why the loop show A two time and not one?
The first time after the do, the print occurs unconditionally. Then the test occurs, and the condition is true (A == A). So the loop starts again, printing A the second time. After that, the test occurs again, and the condition is false (D != A), so the loop terminates.
It prints 67 because (a) you are using the %d decimal number output format, and (b), after the loop ends, *s == 'C' and *t == '\0', and the difference of their ASCII values is 67.
A do...while loop always runs at least once. So on the first iteration, A gets printed. In the condition s points to the first character in its string (A), and t points to the first character in its string ( also A). So it compares ('A'=='A') which is true, then s and t are both incremented to point to the second character in each string (A and B respectively).
On the second iteration, another A gets printed. In the condition it compares ('B'=='A') which is false, then s and t are both incremented to point to the third character in each string. Since the t string only contains two characters, t actually points to the NULL byte at the end of the string.
In the printf, it subtracts the value pointed to by s (C) by the value pointed to by t (a NULL byte, which in your implementation is 0). The ASCII value of C is 67, and 67 - 0 = 0, so 67 is printed.

I know the output of the following code will be 1000 4 but why 1000 4 not 4 1000?

I know the output of the following code will be 1000 4 but why 1000 4 not 4 1000 ?
int a=1000;
printf("%d",printf("%d",a));
I think you forget, that the printf as argument get's first printed and then the return value gets used as parameter for the outer printf statement! That's why you get:
10004
printf("%d", printf("%d",a));
//^^^^ //^^^^^^ 1. prints 1000
//| //| 2. return value get's used for the outer printf statement
//| 3. prints the return value of the inner printf statement 4
The printf function writes a formatted string to the stdout, and returns the number of characters written. In the beginning it writes the value of a which is 1000; after that 4 is returned, and passed to the outer printf invocation that prints 4, thus the output 10004.
In other words, the arguments must be evaluated before the function call is made; the result of printf("%s", a) is given as an argument to the other printf, thus its value must be evaluated before the outer printf can be called.
The arguments to a function are evaluated before a function is called.
printf("%d",a) is executed first, outputting 1000 then printf("%d",4) is called, outputing 4
printf, on success, returns an int equal to the number of characters written. The internal printf gets called first, printing 1000, and then the return of printf (i.e. 4) gets printed.
You're looking at those 'printfs' as they're laid out in the code.
But when actually printing to the console, what matters is order of execution.
And the order is:
first print 1000,
then print value returned from first call to printf.
Hence 10004.
If you wanted to see 41000 as a result you'd have to know value returned from printf before it was called, and that's just, well...

Why does printf("%d\n", printf("%d\b", a)) work this way?

This is my C code, compiled with gcc.
#include<stdio.h>
int main()
{
int a=1;
switch(a)
{
int x=10;
case 1:
printf("%d\n",printf("%d\b",x));
break;
default:
printf("%d\n",printf("%d\b",x));
}
return 0;
}
printf() is supposed to return the number of elements it printed successfully.
printf("%d\b", x) should have printed 10 by itself(since the \b takes the printing pointer one step behind (to the digit 0 in 10) and there is nothing to print after that.
So it should have just printed 10. That is 2 characters. Now the outer printf would display 2.
The output should have been 102.
The output I actually see is 2.
And in case of nested printfs is the printing pointer position remembered? I mean, if there is a \b in the inside printf , it would take the printing pointer one step behind. And when the control now goes to the outer printf, is that changed position remembered? Will it overwrite over that last character?
printf("%d\b",x)
prints the characters '1', '0' (because x==10) and \b. The \b is a backspace character; if you print to a terminal, it will print 10 and then move the cursor back one column.
A call to printf returns the number of characters it printed; in this case, the result is 3 (yes, '\b' counts as a character).
printf("%d\n",printf("%d\b",x));
The inner printf call works as I explained above, and returns 3. The outer printf call prints "3\n".
So the entire statement will print:
10\b3\n
The '\b' causes the 3 to be replace the 0 on the screen, so the final displayed result (when I run the program on my system) is:
13
If I pipe the output through cat -v, I get:
10^H3
where ^H represents the backspace character.
EDIT :
The question was just edited, and the modified program's behavior is quite different. The switch statement causes control to jump past the declaration int x = 10;, but into the scope in which x is declared. As a result, x is uninitialized when printf is called. This causes undefined behavior, and most likely garbage output (I just got -1217572876^H12). If x happens to be 0, I suppose you'd get 0^H2, which would look like 2.
Whatever you're trying to do, please find a better way to do it.

what is the o/p of that program & how it happenes [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Confusion about the output..
#include<stdio.h>
void main()
{
int i=1,j=-1;
if(printf("%d",i)<printf("%d",j))
printf("%d",i);
else
printf("%d",j);
}
here in this program what is the output & how ?
printf returns the total number of characters written. "-1" is longer than "1". So…
The program invokes undefined behaviour because main has to be defined at least as int main() and return either an int or exit has to be called. Especially the output might not be flushed and thus empty.
Supposing the full output appears, the exact output is undefined because the operands of the < can be evaluated in either order. The rest looks trivial.
The if statement needs to be evaluated to take the branch. For this both of the printf calls (made in if statement) will be executed in either order. This will cause 1 and -1 to be printed in o/p buffer but not guaranteed in which datum will be printed first.
Now once value of if condition is known (false), the printf call inside else branch will be executed. It will print 1 in the buffer. At the end as part of exit handler, the o/p buffer will be flushed. This will cause 1-11 or -111 to be printed on the stdout.
answer is <<< 1 -1 1 >>>. Because printf statement returns int value ie number of character successfully written on screen{In if condition, first printf returns 1 and second printf return 2}. So that if condition becomes 1 < 2. This condition is true. So, execute the true block.

Resources