Ca Pe
Ca Pe

Reputation: 3

How to do "not" without "!" in C

In my programming class we are not allowed to use || && and ! for this assignment. How can you do a "not" statement without the use of !? Also, how to do && would be useful but I think I can figure it out.

(we can use % / * pow abs ln + -)

Upvotes: 0

Views: 270

Answers (8)

pburka
pburka

Reputation: 1474

!(variable % 4) can be written as "\1\0\0"[abs(variable%4)].

variable % 4 can only result in the integer values {-3, -2, -1, 0, 1, 2, 3} for any integer value of variable.

Since there are only 7 possible values, we can use a lookup table of the results.

The result of ! on these values is:

  • -3 -> 0
  • -2 -> 0
  • -1 -> 0
  • 0 -> 1
  • 1 -> 0
  • 2 -> 0
  • 3 -> 0

To avoid having to deal with negative indexing, we'll abs the result, so we only see 0-3.

A simple way to represent this lookup table is a literal string: "\1\0\0". We use octal escape sequences for the values. The value at 0 is 1, the value at 1 is 0, etc. C strings have an implicit 0 (NUL) as the final char, and since the last value we need is 0, I didn't explicitly include that.

If you can't use square brackets, you can also write it like this: *("\1\0\0" + abs(variable%4))

Upvotes: 0

Iwillnotexist Idonotexist
Iwillnotexist Idonotexist

Reputation: 13457

How about

1-(abs(abs(a+1) - abs(a-1))/2)

Explanation:

int not(int a){
    int b = abs(a+1) - abs(a-1);
    //b is either -2, 0 or 2 depending on whether a was <0, ==0 or >0.
    int c = abs(b) / 2;
    //c is either 0 or 1 depending on whether b was zero or non-zero
    return 1-c;
    //return 1 if a is 0 or 0 if a is 1
}

Upvotes: 0

Burdock
Burdock

Reputation: 1105

Super easy simple way,

If(x == y) {
    //Don't do something 
 } 
 Else{
     //do something
 } 

Upvotes: 0

kotlomoy
kotlomoy

Reputation: 1430

  • How can you do a "not" statement without the use of !? Also, how to do && would be useful but I think I can figure it out.

Answering exact question: use standard macros not,and etc. Just don't forget to #include <iso646.h>

Upvotes: 1

pburka
pburka

Reputation: 1474

(!x) is equivalent to (x?0:1) or (x==0)

Upvotes: 1

Vaughn Cato
Vaughn Cato

Reputation: 64308

if (!x) { }

is the same as

if (x==0) { }

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112659

!a is equivalent to 1-a, provided a is guaranteed to take only the values 0 or 1.

Upvotes: 1

nhgrif
nhgrif

Reputation: 62052

Depending on the situation, things like:

if(a != b){
   //do stuff
}

Can be rewritten as:

if(a == b){} else {
  //do stuff
}

Upvotes: 0

Related Questions