logical operators - find difference

Dec 29, 2012 at 12:44pm
hi,

I'm learning programming and I can't make this script work. I opened 2 files and I want to go thru them and find out, if there are same or how many characters are different. But none of the cycles bellow work. Can you tell me, what I have done wrong? Thank you.
(I'm 100% sure that the problem lies here)


while(((c = getc(fr)) != EOF) && ((v = getc(fw)) != EOF))
if(c != v )
diff++;

while(((c = getc(fr)) && (v = getc(fw))) != EOF)
if(c != v )
diff++;
Dec 29, 2012 at 12:52pm
c and v should be of type int because EOF can't be represented by a char.

The first code looks more correct but it will fail to notice if the files have different sizes. If you want to increment diff once for each extra byte that the other file have you can just change the && to ||.
Dec 29, 2012 at 1:12pm
(In the first file there are 59 and in the second 62 chars) If I change && to || in first cycle it will sum characters from first and second file and it will display 121. "c" and "v" are integers.
Dec 29, 2012 at 4:48pm
No that is not what will happen. If the first 59 characters are the same in both files diff will be incremented 3 times, so if diff has value 0 before the loop it will have value 3 after it.
Dec 30, 2012 at 3:18pm
3 is the answer, but using script:

int diff = 0;
int c;

while(((c = getc(fr)) != EOF) || ((v = getc(fw)) != EOF))
if(c != v )
diff++;

printf("%d", diff);

shows 121 and I don't know why. :(
Dec 30, 2012 at 3:46pm
> 3 is the answer, but ... shows 121 and I don't know why

You do know why.

How is e1 || e2 evaluated?
When e1 is true?
When e1 is false?
Topic archived. No new replies allowed.