Reputation: 23
I am new to C, and in StackExchange here and all other sources, 0
is success, else is false
. In this function to print prime numbers, why does it only print prime numbers if return
value is 1?
like if I go (is_prime(num) == 0)
, then it will not print prime number, but if just said is_prime(num)
it automatically assumes (is_prime(num) == 1)
?
This has confused me, please clarify because the value will switch between 0 and 1, but why the bias automatically?
int is_prime(int num){
int isPrime = 1;
int i;
for(i = 2; i <= sqrt(num); i++){
if(num % i == 0){
isPrime = 0;
}
}
return isPrime;
}
Upvotes: 2
Views: 1905
Reputation: 361585
I am new to C, and in StackExchange here and all other sources, 0 is success, else is false.
That's backwards. In C, 0 is false and non-zero values are true.
if (number) <==> if (number != 0)
if (!number) <==> if (number == 0)
This is true most of the time and is the most common integer → boolean relationship. There are a few exceptions where the mapping is reversed:
The return value of main()
is 0 for success, non-zero for failure. The reason for this is if a program fails you may want to distinguish between errors by returning different exit codes. For instance, 1 for "bad command line arguments", 2 for "file not found", 3 for "could not connect to server", etc. The meaning of these exit codes is application-dependent.
Many POSIX system calls such as close()
and connect()
use the same idea, returning 0 for success and -1 for errors. For these functions you must write if (connect(...) != 0)
rather than if (connect(...))
.
Note that these exceptions are not part of the C language itself, but rather with commonly-used C functions.
Upvotes: 3
Reputation: 4733
In an if statement, or any case where a boolean value (True or false) is being tested, in C, at least, 0
represents false, and any nonzero integer represents true.
If, for some reason, your isPrime function returned -17
given some input x
, isPrime(x)
would still be considered true if taken as a boolean, and thus if you had some code inside an if block whose condition was isPrime(x)
, that code would be run, because -17
is nonzero.
Upvotes: 1