This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[PATCH][BZ #14450] Fix timeval example in manual


Hi,

The timeval_subtract example in the manual is incorrect when the input
values have a negative result.  Attached patch fixes this.  OK to
commit?

Siddhesh


2012-12-10  Guillaume Foliard  <guifo@wanadoo.fr>
 
	[BZ #14450]
	* manual/examples/timeval_subtract.c (timeval_subtract): Fix
	timeval example.

diff --git a/manual/examples/timeval_subtract.c b/manual/examples/timeval_subtract.c
index f0f2375..35c562d 100644
--- a/manual/examples/timeval_subtract.c
+++ b/manual/examples/timeval_subtract.c
@@ -23,23 +23,38 @@ int
 timeval_subtract (result, x, y)
      struct timeval *result, *x, *y;
 {
+  struct timeval *a, *b;
+  int sign;
+
+  if ((x->tv_sec < y->tv_sec)
+      || ((x->tv_sec == y->tv_sec) && (x->tv_usec < y->tv_usec))) {
+    a = y;
+    b = x;
+    sign = 1;
+  }
+  else {
+    a = x;
+    b = y;
+    sign = 0;
+  }
+
   /* Perform the carry for the later subtraction by updating @var{y}. */
-  if (x->tv_usec < y->tv_usec) {
-    int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
-    y->tv_usec -= 1000000 * nsec;
-    y->tv_sec += nsec;
+  if (a->tv_usec < b->tv_usec) {
+    int nsec = (b->tv_usec - a->tv_usec) / 1000000 + 1;
+    b->tv_usec -= 1000000 * nsec;
+    b->tv_sec += nsec;
   }
-  if (x->tv_usec - y->tv_usec > 1000000) {
-    int nsec = (x->tv_usec - y->tv_usec) / 1000000;
-    y->tv_usec += 1000000 * nsec;
-    y->tv_sec -= nsec;
+  if (a->tv_usec - b->tv_usec > 1000000) {
+    int nsec = (a->tv_usec - b->tv_usec) / 1000000;
+    b->tv_usec += 1000000 * nsec;
+    b->tv_sec -= nsec;
   }
 
   /* Compute the time remaining to wait.
      @code{tv_usec} is certainly positive. */
-  result->tv_sec = x->tv_sec - y->tv_sec;
-  result->tv_usec = x->tv_usec - y->tv_usec;
+  result->tv_sec = a->tv_sec - b->tv_sec;
+  result->tv_usec = a->tv_usec - b->tv_usec;
 
   /* Return 1 if result is negative. */
-  return x->tv_sec < y->tv_sec;
+  return sign;
 }


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]