Re: Direct computation of integer limits in K&R2?



santosh wrote:
Hello all,

In K&R2 one exercise asks the reader to compute and print the limits for
the basic integer types. This is trivial for unsigned types. But is it
possible for signed types without invoking undefined behaviour
triggered by overflow? Remember that the constants in limits.h cannot
be used.


C90:

The original exercise text as provided by Richard Heathfield is:

Exercise 2-1. Write a program to determine the ranges of char, short, int, and long, both signed and unsigned, by printing appropriate values from standard headers and by direct computation. Harder if you compute them: determine the ranges of the various floating-point types.


Any ideas?


I think the text gives us space, in the signed int case to see if INT_MIN== -INT_MAX-1 or INT_MIN== -INT_MAX, and act accordingly with unsigned int:


#include <stdio.h>
#include <limits.h>


int main()
{
unsigned x= -1;

int INTMIN, INTMAX;

printf("INT_MIN= %d, INT_MAX= %d\n", INT_MIN, INT_MAX);

if (INT_MIN== -INT_MAX -1)
{
INTMAX=x /2;

INTMIN= -INTMAX -1;
}

else
{
INTMAX=x /2;

INTMIN= -INTMAX;

}


printf("INTMIN= %d, INTMAX= %d\n", INTMIN, INTMAX);


return 0;
}



Probably this is a stupid solution. But what can we take for granted, "by printing appropriate values from standard headers"?
.



Relevant Pages

  • Re: Add Method
    ... Do you mean to convert the number to a string? ... My guess is that this is an exercise for a 1st-year computer science course ... and it means to convert positive number (probably in an int) into a String ...
    (comp.lang.java.help)
  • Re: race condition during termination process
    ... There are 2 exercise at the last part of chapter 7.7(Threads ... But I couldn't find the cause of race condition and the solution. ... int request_index; ...
    (comp.programming.threads)
  • Re: Degenerate strcmp
    ... Uses %d as a format specifier for a size_t... ... int, maybe these two bugs cancel each other out. ... The compiler will arrange ... off makes this sort of exercise rather odd. ...
    (comp.lang.c)
  • K&R Exercise 1-21: entab
    ... I've been working hard on the entab program in K&R Exercise ... eight blanks with tabs, but no other strings of blanks. ... int getline; ...
    (comp.lang.c)
  • race condition during termination process
    ... Have you ever heard about lupg's multithread tutorials? ... There are 2 exercise at the last part of chapter 7.7(Threads ... int request_index; ...
    (comp.programming.threads)