As far as I know, impure functions are those which do not always return the same value when called with the same parameters (I must be missing something, or may be wrong, correct me if I am).
So why is printf() considered to an impure function?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A "pure" function lacks side-effects too.
In other words, no matter how many times you call it, a pure function will affect nothing other than its output.
For example,
foois impure, even though it return zero:If
foowere pure, calling it would not affect the result ofbar().printfis impure because its result has "side effects" — specifically, it prints something on the screen (or in a file, etc).If it were pure, then you could call it a billion times and be sure nothing bad would happen.
But if you actually call
printfa million times, there certainly is a difference to the user — it fills up his screen (or disk space, or whatever). So clearly it’s not pure.Furthermore: If your output was redirected to be your own input (somewhat useless, but still), then calling
printfwould affect what you would receive fromgetchar. 🙂 So it’s directly observable that way, too.