How to implement this while not from Python in C?

1

I am studying a code in Python that I need to transform to C, but the part that is confusing me is this:

while not(f1 == 0 and fn == 1):
    ...

How would this same C code be?

    
asked by anonymous 04.09.2018 / 22:34

2 answers

4

There is no while not , there is the not operator that is independent of while .

If you want to apply only not you have to change this operator that uses the English word by the symbol ! which is what C uses. But you have to use it in the right place. And the and you exchange for && .

while (!(f1 == 0 && fn == 1)) {

Note that in C parentheses of while are part of their construction and are not suitable for grouping an expression. Since you need to group everything to apply the operator throughout the expression then you need to create other parentheses.

This occurs in Python because in this language the parentheses are not part of the while construct.

So even the most correct in Python would look like this:

while not (f1 == 0 and fn == 1):

It's a blank space that seems unnecessary, but it makes all the difference for readability, since the way it was written looks like it's a function.

But the most correct is to just reverse all the signals:

while (f1 != 0 || fn != 1) {

This saves one operation and may even make it easier to short circuit and save another. And for those who know it is even more readable.

If everything is denied then what is equal becomes different, and what is a and , turns a or . Actually in Python it should look like this too:

while f1 != 0 or fn != 1:

Without the parentheses that can confuse when you convert from one language to another. So it becomes clear that there is no while not , but the parentheses and the lack of space gave the impression of while not being one thing.

I'll show you how to do this. And that the inversion of all operators is the same as applying ! .

#include <stdio.h>

int main(void) {
    int f1 = 1;
    int fn = 1;
    printf("%d ", f1 == 0 && fn == 1);
    printf("%d ", !(f1 == 0 && fn == 1));
    printf("%d\n", f1 != 0 || fn != 1);
    f1 = 0;
    printf("%d ", f1 == 0 && fn == 1);
    printf("%d ", !(f1 == 0 && fn == 1));
    printf("%d\n", f1 != 0 || fn != 1);
    while (f1 != 0 || fn != 1);
}

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

Do not forget that in C, unlike Python that uses indentation and only needs to open with : , you have to close the keys when the block ends. Then I made a while without a block so it ended with ; . But more common is:

while (f1 != 0 || fn != 1) {
    ...
}
    
04.09.2018 / 23:09
2

The direct translation to C would be as follows:

while (!(f1 == 0 && fn == 1)) { ... }

However, this can be simplified by using the De Morgan law for this:

while (f1 != 0 || fn != 1) { ... }
    
04.09.2018 / 23:07