Posts Tagged ‘c’

Programming Language Rant

November 15th, 2011 5 comments


C programmers love to gloat that recursion can not be done in Fortran. When they say Fortran, they mean FORTRAN 77, since they absolutely refuse to acknowledge the existence of modern Fortran 90. (Fortran 90 came out over ten years ago. You would think they might know something about it by now!) But this example shows that even in FORTRAN 77 one can quickly and easily write routines that are recursive. So stick that in your complex variables, C programmers, and — oh wait, I forgot there are no complex variables in C. You have to manually define a complex data type. Not to mention having to write math functions like sin( ) and cos( ) to handle such data types.

Hahaaa … love it!

Categories: c/c++, nerdcore Tags: , ,

Weihnachtsrätsel 3.12.

December 3rd, 2009 Comments off

Welche numerische Funktion/Algorithmus realisiert folgende C Funktion?

Wegen Schwierigkeiten mit dem Code, jetzt als Bild.


Zum Weihnachtsrätsel.

Categories: nerdcore Tags: ,

external variables: C vs. C++

July 7th, 2009 No comments

The situation is the following: We have two source files (main and core) and want to use the same global variable (headvar) in both of them. In C thats plain easy:


#ifndef __HEAD_H__
#define __HEAD_H__
int headvar; /* global var */
int core(int);  /* forward declaration */
#endif /* __HEAD_H__ */


#include <stdio .h>
#include "head.h"
int main()
        printf( "Hello World!\n" );
        printf("headvar: %d\n", headvar);
        printf("core: %d\n", core(23));
        return 0;


#include "head.h"
int core(int var)
    int res=0;
    return res;

In C++ this isn’t going to work as the variable is basically declared twice using the mechanisms as seen above. The reasons for that are quiet complex – you can gain more insight here: I’ll only talk about the solution here. You have to make sure that there is only one single memory allocation aka instance of the variable. To ensure this you can use the keyword “external” to tell the compiler-suite that the actual definition occurs elsewhere. Using external you basically tell that there is a name refering to a variable of the given type without actual declaration. You can use this external variable in multiple locations as long as there is one single declaration in one location. So here is the sourcecode of above recoded in C++.


#ifndef __HEAD_H__
#define __HEAD_H__
extern int newvar; /* external declaration */
int core(int);  /* forward declaration */
#endif /* __HEAD_H__ */


#include <iostream>
#include "head.h"
int newvar = 1;	/* actual definition */
int main()
	std::cout < < "Hello World!" << std::endl;
	std::cout << "newvar: " << newvar << std::endl;
	std::cout << "core: " << core(23) << std::endl;
    return 0;


#include "head.h"
int core(int var)
    int res=0;
    newvar=42; /* new value for variable defined in main.cpp */
    return res;

This is nothing new for the casual programmer but can be a real pain in the ass when the error has already been made as the error-messages are mostly “slightly” irritating.

Categories: c/c++ Tags:

Displaying Enum-Names instead of Values in Errors

June 4th, 2009 1 comment

The usual lazy developer likes to print out plain error messages, which contain pure numbers and don’t mean anything. The most prominent example is Windows itself, back in the old days.

Some time ago I was once again faced with the decision how to handle errors in our plug-able class design. While trying to find a good solution I remembered an old blog post – Qt is able to create a mapping from enum integer values to their respective names. So I fiddled around a bit and came up with a pretty neat solution, which requires virtually no extra code to gain a little more meaningful error messages than plain integer values.

Here is what I came up with:

You need to sub-class an error base class, insert your error enumeration, and tell Qt that you need the value-to-name mapping for this enum. All the extras come with the base class.
If you don’t like the rest of the class, you might just want to check out BaseError::identifierToName(). That’s where the magic is happening.

A usage example:

 // --- header file ---
 class HorseError : public BaseError
     enum x { DOES_NOT_WANT, IS_INJURED };
 class Horse
     HorseError error;
     void ride();
 // --- source file ---
 void Horse::ride()
     error.activate(HorseError::DOES_NOT_WANT, "cannot happen anyways");
 // --- using ---
 Horse mybeautifulhorse;
 // operator() returns a bool
 if (mybeautifulhorse.error()) {
    // operator QString makes the error readable
    qDebug() < < mybeautifulhorse.error;

The Header File – BaseError.hpp

class BaseError : private QObject                                                                                                         
    virtual ~BaseError();
    /** @returns whether the error is active */
    bool active() const;                       
    /** @returns the identifier (an enum) */   
    int identifier() const;                    
    /** @returns the name of the identifier enum e.g. "MyErrorClass::MyReturnValue" */
    QString name() const;                                                             
    /** @returns the description given by activate's second parameter */              
    const QString& description() const;                                               
    /** throw the error */
    void activate(int identifier, const QString& description = QString());
    /** clear the state / remove the error */                             
    void deactivate();                                                    
    /** alias for active() */
    bool operator()() const; 
    /** @returns 'name() "description()"' e.g.
     * 'MyErrorClass::MyReturnValue "something meaningful"'
    operator QString() const;                              
    /** emitted when the error has been activated */
    void activated();                               
     * Default implementation generates a string using the
     * "DerivedErrorClassName::EnumeratorValueName"       
     * @note                                              
     * reimplement this functions to apply an own         
     * identifier-to-error-name-mapping                   
    virtual QString identifierToName(int identifier) const;
    bool m_active;
    int m_identifier;
    QString m_description;

The Source File – BaseError.cpp

#include "BaseError.hpp"
#include <qmetaenum>
BaseError::BaseError() : QObject(), m_active(false)
bool BaseError::operator()() const
    return m_active;              
BaseError::operator QString() const
    return QString("%1 \"%2\"").arg(name()).arg(description());
int BaseError::identifier() const
    return m_identifier;         
QString BaseError::name() const
    return identifierToName(m_identifier);
const QString& BaseError::description() const
    return m_description;
void BaseError::activate(int identifier, const QString& description)
    m_identifier = identifier;
    m_description = description;
    m_active = true;
    emit activated();
void BaseError::deactivate()
    m_active = false;
QString BaseError::identifierToName(int identifier) const
    QStringList ret;
    const QMetaObject* meta = metaObject();
    for (int i=0; i < meta->enumeratorCount(); ++i) {
        QMetaEnum enumerator = meta->enumerator(i);
        ret < < QString("%1::%2").arg(enumerator.scope()).arg(enumerator.key(identifier));
    return ret.join(", ");

Categories: c/c++, qt, software Tags: , , , , ,

source code comments update

April 26th, 2009 1 comment

One of the posts in yesterdays article (source-code-comments) was about a function used in the Quake3 sources. I fiddled around with it to understand what it does and am amazed of the compute power of this little snippet:

#define _GNU_SOURCE
#include <assert .h>
#include <stdio .h>
#include <stdlib .h>
#include <math .h>
float Q_rsqrt( float number )
  long i;
  float x2, y;
  const float threehalfs = 1.5F;
  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;  /* evil floating point bit level hacking */
  i  = 0x5f3759df - ( i >> 1 ); /* what the fuck? */
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) ); /* 1st iteration */
  /* y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed */
  #ifndef Q3_VM
  #ifdef __linux__
    assert( !isnan(y) ); /* bk010122 - FPE? */
  return y;
main (int argc, char *argv[])
    char * line = NULL;
    size_t len = 0;
    float input=42.23;
    printf("type in a float e.g: 42.23\nvalue: ");
    getline(&line, &len, stdin);
    input = strtof(line, (char **) NULL);
    printf ("reverse square root of %.6f is %.6f \n", input, Q_rsqrt(input));
    if (line) free(line);
    return 0;
 gcc -ansi -pedantic -Wall -D_XOPEN_SOURCE=600 Q3_inv_sqrt.c -o Q3rsqrt

Categories: linux, nerdcore, software Tags: ,

Böser Code: member pointer in C++

April 14th, 2009 No comments

Vor einiger Zeit in ich auf etwas aufmerksam geworden, das mir erstauntes Kopfschütteln entlockt hat – member pointer.
Aber vorher etwas C++-Theorie 😉

Das Klassenkonstrukt in C++ kennt u.a. die Schlüsselwörter public und private, die dazu dienen den Zugriff auf so markierten Member der Klasse zu beschränken. public steht dabei für allgemeinen Lese- und Schreibzugriff, privat beschränkt den Zugriff auf Memberfunktionen der Klasse. Dazu ein kurzes Beispiel:

class someClass{
      int one;        // öffentliche Variable
      void f();
      int two;        // private Variable
someClass Instance;
... = 1;        // erlaubt
Instance.two = 2;        // verboten - compiler error

Member Pointer sind eine spezielle Form von Zeigern, die nur auf Member von Instanzen von der selben Klasse zeigen dürfen. Realisiert wird das durch relative Addressierung im Speicherbereich der Klasseninstanz. Für obriges Beispiel sieht das zum Beispiel so aus.

// pMember ist global und zeigt auf 'one' einer beliebigen Instanz von 'someClass'
int someClass::*pMember = &amp;someClass::one;
Instance.*pMember = 5;     // erlaubt, da 'one' public ist
pMember = &amp;someClass::two;     //    compiler error, da
Instance.*pMember = 23;            //     'two' private ist

Hübsche Syntax oder? 😉 Nebenbei ist ‘.*‘ keine Kombination aus Punkt- und Dereferenzierungsoperator, sondern stellt einen eigenständigen Operator für member pointer dar.
Bis hierhin ist das noch absolut stressfrei, da private greift und den Zugriff beschränkt. Anders sieht das allerdings aus, wenn der Zeiger seinen Inhalt innerhalb der Klasse bekommt. Hier kommt die Member-Funktion ‘f()‘ ins Spiel.

void someClass::f()
   pMember = &amp;someClass::two;        // erlaubt, da innerhalb der Klasse!
Instance.f()                    // Sesam öffne dich:
                                 // ab hier hat private seine Bedeutung verloren !
Instance.*pMember = 42;        // erlaubt aber BÖSE :)

In der Praxis kommen Zeiger auf Member-Variablen recht selten vor. Pointer auf Member-Funktionen sind damit aber auch möglich und wohl sinnvoller. Zum Abschluss lass ich die Syntax nochmal für sich selbst sprechen.

void (someClass::*pFunc)() = &amp;someClass::f;    // Deklaration
(someInstance.*pFunc)();                            // Aufruf

Categories: software Tags: , , ,

C/C++ Pointer-Arithmetics

February 17th, 2009 8 comments

I recently found this when looking up how C/C++ organizes memory when allocating arrays, specifically multi-dimensional arrays.

You can access the array

#define X 5
#define Y 10
int data[X][Y];

either using



*(*(data + x) + y)

Categories: software Tags: , ,