+ 1

Please why is it printing out "they are equal "

https://code.sololearn.com/W5iFaoJWP6qz/?ref=app why isn't it printing out b since a isn't assigned to b

2nd Apr 2018, 4:20 AM
Sammy
Sammy - avatar
13 odpowiedzi
+ 2
use if (a==b) instead of if (a=b) if (a=b) will assign b to a, instead of doing a comparison.
2nd Apr 2018, 4:28 AM
Emma
+ 2
It's because it's failing to open the file called 'file'. fopen returns null on failure, which is equal to zero. In an if statement, 0 means false, and non-zero values mean true. if (fp = fopen("file", "w")) { console.log("yes") // File to open the file. } else { console.log("no")// Process the file. } On failing to open a file: if (fp = fopen("file", "w")) evaluates to: if (fp = null) which evaluates to: fp = null; if (0) which leads to the else statement being actioned. if (0) can be thought of as if (false) On succeeding to open a file: if (fp = fopen("file", "w")) evaluates to: if (fp = 4467544) or some such value, which evaluates to: fp = 4467544; if (4467544) which can be thought of as: fp = 4467544; if (true)
2nd Apr 2018, 5:41 AM
Emma
+ 2
Xan: fopen() doesn't not exist in javascript, until you define a custom so named function, as OP done in its last example code, by defining an empty fopen() function, which always return 'undefined' so, the condition is always false ^^
2nd Apr 2018, 11:10 AM
visph
visph - avatar
+ 2
Apologies! Very late night. I was mixing up javascript and C! Thanks for pointing that out :-)
2nd Apr 2018, 12:29 PM
Emma
+ 1
OK thanks xan
2nd Apr 2018, 4:32 AM
Sammy
Sammy - avatar
+ 1
but why didn't it take note that it wasn't assigned.... why did it have to assign under if statement?
2nd Apr 2018, 4:33 AM
Sammy
Sammy - avatar
+ 1
You might want to do something like this, in which case the assignment makes sense. A compiler doesn't have much intelligence. As long as your code parses correctly, it doesn't care about common sense! if (fp = fopen("file", "w")) { // Process the file (file was opened for writing). } else { // Report an error (file could not be opened for writing). }
2nd Apr 2018, 4:48 AM
Emma
+ 1
k thanks again xan
2nd Apr 2018, 5:09 AM
Sammy
Sammy - avatar
+ 1
I ran it here
2nd Apr 2018, 5:12 AM
Sammy
Sammy - avatar
+ 1
and it returned no
2nd Apr 2018, 5:13 AM
Sammy
Sammy - avatar
+ 1
Apologies, I've updated my comment!
2nd Apr 2018, 5:17 AM
Emma
+ 1
please I don't understand because it is running the else statement
2nd Apr 2018, 5:33 AM
Sammy
Sammy - avatar