Signed / Unsigned Integer Comparison

I found this question on a beginner test and I thought it was interesting.

Q. What is the output of the following lines of code?
[PHP]
int a = -1;
unsigned int b = 1;

if (a > b )
std::cout << “Foo”;
else
std::cout << “Bar”;
[/PHP]

Extra:
Q. Write code that generates random numbers. Do not use functions/libraries that generate random numbers.

Cheers!

Hata Rao hakuelewa ‘logs’ na hasumbui…
Ooo…alisumbua kidogo tu

1 Like
the answer is foo
1 Like

Explain it. And the extra question?

$num = array(1,2,3,4,5,6,7,8,9);
echo array_rand($num);

I got confused abit by PHP quote above, the code is in c++ and the answer is bar by default int is signed in c++
signed numbers are both negative and positive numbers
unsigned are only positive numbers

@TerribleWaste do you have a idea where i can get jobs aggregator in Kenya, that is a i have a contract to create a job searching website like jobwebkenya.com, bestjobskenya.com.
Where do they get they data coz all these websites show same jobs but use different user interface

I am not sure about that. There should be a few WP plugins that can do close to what you want. If not then good old scraping…

1 Like
$num = microtime();
$num = rand(1000,9999);

You are cheating. You can start by looking at this page: https://en.wikipedia.org/wiki/Linear_congruential_generator

[CODE]# python code
import random
print(random.randint(x,y))

#Returns a random integer N such that x < N < y[/CODE]

You imported a library (random). The Q was to write a pseudo-random number generator from scratch.

hehehe random is a module in this case, wacha irudi dojo

The Intel processor family contains an instruction rdtsc which can be used to implement random number generator however that approach is not portable across different processors.

int random(int limit)
{
     int x;
     __asm__("rdtsc": "=d" (x) );
     return x % limit;
}
1 Like

Explanation: The int is promoted to unsigned int. Because its most significant bit is 1(negative sign bit when not unsigned), a is a much larger number than b.

Yeah. Absolutely correct.