2009-12-15

A floating point and C++ templates

Find a bug in the following line:
double sum = std::accumulate(V.begin(), V.end(), 0);


Think more...


This bug can't be easiliy avoided as the connection between internal accumulator variable, return value and third argument types is not obvious and is very well incapsulated by implementation.

The right answer is:
double sum = std::accumulate(V.begin(), V.end(), double(0)); //0.L gives off the same effect

Here is GNU implementation of template function in question:

/**
* @brief Accumulate values in a range.
*
* Accumulates the values in the range [first,last) using operator+(). The
* initial value is @a init. The values are processed in order.
*
* @param first Start of range.
* @param last End of range.
* @param init Starting value to add other values to.
* @return The final sum.
*/
template
inline _Tp
accumulate(_InputIterator __first, _InputIterator __last, _Tp __init)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator>)
__glibcxx_requires_valid_range(__first, __last);

for (; __first != __last; ++__first)
__init = __init + *__first;
return __init;
}

2009-11-12

Empty structures in C and C++

//test.c
#include <stdio.h>

struct Temp0{};
struct Temp1{char a;};

int main() {
printf("Temp0 size: %d\n", sizeof(struct Temp0));
printf("Temp1 size: %d\n", sizeof(struct Temp1));
return 0;
}


This code being compiled with GNU toolchain gives the following results:

$ gcc test.c -o test && ./test
Temp0 size: 0
Temp1 size: 1



$ g++ test.c -o test && ./test
Temp0 size: 1
Temp1 size: 1


The reasons explained

I wonder are other toolchains give the same results...

2009-07-10

Gnome-terminal and gconf

Recently there was a usual problem with gnome-terminal in Debian testing. As gconf is updated, gnome-terminal won't start gconf by itself.
Manual update of gnome-terminal (to version 2.26) from unstable release solves the problem.