Path: utzoo!attcan!uunet!mcvax!ukc!etive!aiai!ken From: ken@aiai.ed.ac.uk (Ken Johnson) Newsgroups: comp.lang.c Subject: Detecting overflow Message-ID: <455@skye.ed.ac.uk> Date: 18 May 89 10:58:56 GMT Reply-To: ken@aiai.UUCP (Ken Johnson) Organization: AIAI, University of Edinburgh, Scotland Lines: 27 Since I posted a C program which detects overflow in int multiplication at immense cost in time terms, I received the following solution by e-mail: if ( a != 0 && (a * b)/b == a) { /* No overflow */ } My first thought is the first test should really be applied to b, not a, to prevent overflow, giving if ( b != 0 && (a * b)/b == a) { /* No overflow */ } However, this is not always going to work. Consider the case of a = 512 (0x200), b = 64 (0x40). Then in 16-bit arithmetic, a != 0 is true b != 0 is true (a * b) = 0x8000 (overflowing) but 0x8000/0x40 = 0x200 ...so I don't think this is guaranteed to work either. A further example would be 521 * 63 (0x209 * 0x3f). -- Ken Johnson, AI Applications Institute, 80 South Bridge, Edinburgh EH1 1HN E-mail ken@aiai.ed.ac.uk, phone 031-225 4464 extension 212 Half of what I have said in this article is rubbish. I don't know which half.