Manipulating Integers
The Sign of Integers
You should now write your first C program on your own:
- Create a new empty file
integers.c
. - Write a function
isNegative
, which takes a signed integer (int
) as an argument and returns a boolean value. The function should returntrue
when the value of the integer argument is negative,false
otherwise. - Then write a
main
function (as seen in the lecture and on the previous page). Call theisNegative
function with some test values and display the return values using theprintf
function. Don't forget the#include
statements forstdio.h
andstdlib.h
. Themain
function should always returnEXIT_SUCCESS
. - Compile the code, using the usual compiler arguments, fix any compiler errors.
- Run the program and make sure that the output, i.e., the return values of the calls to the
isNegative
function, is correct.
The Sign of Integers using Arithmetic
You know that the lab machines use the two's complement representation with 32 bits for signed integer numbers of type int
. This means that the sign is explicitly encoded in the number representation.
- Make sure to use the type
bool
as a return type. Recall,bool
is not a keyword of the C language. Instead this type is defined in the library. - Rewrite the
isNegative
function so that it only contains a single return statement and only contains arithmetic operations. - Consequently, your code should not use any comparison operators (
<
,<=
, ...) or use any conditional constructs, such asif
statements or the conditional operator (? :
). - Compile the code as usual, fix any compiler errors.
- Make sure that the output produced by your program did not change.