Question

doing some exam prep and this is a past question.

Describe what the following pieces of C do and re write in a simple programming style with the same functionality. (The bad indentation was the intention of the question).

With regards to section A i'm not sure what unsigned cast is doing to a. I have tested it a few times and can't seem to get a result that makes sense.

Similarly In B im not sure what how the while loop is working with the long cast and the !! being another problem

The Code : //code section A

int f(int a,int b){
  return(((unsigned) a)>b);}

//code section B

int h(int *x, int y){
int * z= x-- +y; 
w=0;
while( (long) z-- ^(long) x) w += !!(*z);
return w;}

Any help would be appreciated, Thank you.

Was it helpful?

Solution

!! negates a boolean expression twice, essentially converting an expressions value to 0 or 1.

As in C all values other than zero mean true, and zero means false, !! can be used to convert it into 0 or 1, in the case you need to use it later in a function or expression which doesn't accept any value for true, only the number 1.

About the rest: unsigned interprets the internal representation of your int a from your function argument to unsigned int, so for example -1 becomes 4294967295 if your compiler uses two's complement and 4 byte ints.

About the casting to long : I strongly recommend against in similar situations unless you absolutely know what you are doing. In your example, it does some pointer arithmetic, in interpreting your pointer as numeric values, essentially working with the addresses of your variables as if they were just numbers. They have probably chosen long because on their system it had the exact same size as a pointer. This is not guaranteed to be so on all systems.

So, to give a very short answer to your question: The code does undefined behavior with those expressions, except for the !! which just give 0 if the expression was zero, and 1 otherwise.

OTHER TIPS

The operator ! is the logical negation.

!true is false (0), and !false is true (1).

When a value is used as a boolean value, anyhting other than 0 (0 in a large sense) is true; 0 is false.

So, !!(*z) has either the value 0 or 1.

It will be 0 if *z was NULL to begin with
It will be 1 if *z was not NULL.

! is the boolean operator for not.

false is 0, and true is 1 in C.

So when you take any int, which is not 0- and you run ! on it, you'll get 0 (true becomes false), and zero will become one .

So the action of !! is changing each non-zero value to 1 , and leaving each 0 a 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top