martedì 10 maggio 2011
Qt, il kit di sviluppo e' 1.1
domenica 17 aprile 2011
Oracle intende affidare lo sviluppo di OpenOffice.org alla community
Oracle trasformerà OpenOffice.org in un progetto interamente gestito dalla comunità e non ne offrirà più una versione commerciale. La nota è stata diramata ieri ed è destinata a fare discutere: la community cui fa riferimento Oracle non è certo quella di LibreOffice, perciò potremmo anche avere due suite equivalenti in competizione.
La multinazionale continuerà a supportare gli standard di Open Document Format (ODF) e a sviluppare la propria soluzione per l’ufficio, Oracle Cloud Office. Edward Screven sostiene che Oracle intenda «iniziare subito a collaborare con la comunità perché OpenOffice.org mantenga il proprio successo». Non cita The Document Foundation.
La prospettiva più probabile è quella d’avere, quindi, due progetti paralleli. Un po’ come KOffice e Calligra Suite, il fork interno a KDE. Qualunque sia il futuro di OpenOffice.org e LibreOffice, la comunità open source ha solo da guadagnarci: è davvero un peccato che Oracle non abbia predisposto altrettanto anche per OpenSolaris.
Via | Marketwire
Oracle intende affidare lo sviluppo di OpenOffice.org alla community é stato pubblicato su ossblog alle 09:00 di sabato 16 aprile 2011."
domenica 10 aprile 2011
Grep, la storia del suo nome
Grep è uno dei più importanti strumenti a disposizione dal terminale di un sistema operativo unix-like. Per chi non l’avesse mai utilizzato non sapesse di cosa stiamo parlando si tratta di un programma che ricerca un pattern di testo all’interno di file.
La sua potenza e versatilità è innegabile ed è alla base di molti script che potete trovare sulla vostra macchina, come potete verificare con una ricerca su /usr/bin/: grep grep /usr/bin/* | cut -f 1 -d : | uniq | grep -v binario | wc -l. Ma come mai questo programma ha questo nome strano?
La risposta affonda nella notte dei tempi unix quando si usava ancora il famoso editor di test “ed”. Con il crescere della popolarità delle espressioni regolari ed fu dotato della possibilità di stampare le linee del file aperto che soddisfacevano un determinato pattern. La sintassi era la seguente: g/regex/p e tradotta significa: ricerca globalmente (ovvero in tutto il file e non in una sola linea) una espressione regolare (regular expression) e mostra (print) le corrispondenze trovate.
Una funzionalità così utile che Ken Thompson creò la prima versione di grep adattando il codice del parser delle espressioni regolari di ed. La data di nascita è ricordata come il 3 marzo 1973 e dopo quasi quarant’anni il programma gode di una grande fama ed ha molte caratteristiche che i suoi antenati non avevano.
Via | Linuxers
Grep, la storia del suo nome é stato pubblicato su ossblog alle 10:00 di mercoledì 06 aprile 2011."
martedì 5 aprile 2011
mercoledì 30 marzo 2011
Summary of various recommendations about desired competencies of software developers
1. Ability to accommodate himself to others, empathy, “be the customer” mentality – genuine interest in understanding what other people are trying to accomplish and based on this understanding think about creating technical solutions to help them reach their goals. Genuine interest in understanding “why to create software” and the broader context of software systems. Cognitive task analysis. Appreciation of unstated requirement and ability to identify these. Listening skills, approachable, and respect for people. Ability to work in homogeneous, multi-disciplinary, multi-locational and multicultural teams. Ability to work under supervision and constraints, Understanding of the impact of personal character and behaviors on others.
2. Ability to apply knowledge, ability to integrate the application of knowledge, skills, and sense of responsibilities to new settings and complex problems.
3. Ability to see the self as bound to all humans with ties of recognition and concern. Seek help from other, Ability to help and assist others, mentoring, commitment to others’ success. Sensitivity towards global, societal, environmental, moral, ethical and professional issues, and sustainability. Respect for the intellectual property of others. Work ethics.
4. Abstraction and transition between levels of abstraction, representation skills spatial and temporal modeling skills, structuring skills, and theorizing.
5. Algorithmic and structured thinking. Logic, pattern matching, logical what-if analysis, problem decomposition and synthesis, etc.
6. Analytical skills.
7. Communication skills.
8. Constructive criticism.
9. Curiosity, interest in ‘how things work’ and ‘how to create things that work,’ interest in the power of technology, humility, observation skills, ability to see things as they are, broader understanding and interests, respect for the classic authors of the great books, openness to constructive criticism, value and readiness for lifelong learning. Active listening skills. Ability to develop a very good understanding of domain specific vocabulary, its semantics, and established thinking patterns.
10. Decision making skills.
11. Design skills.
12. Domain competence.
13. Entrepreneurship, intrinsic motivation to create something, desire to improve things, initiative taking, enjoy challenges, sense of mission, perseverance, concentration, result orientation, commitment, self motivation, dedication, and hard work. Adaptability, flexibility, open-mindedness, and ability to multi-task. Sense of urgency and stress management.
14. Experimentation skills.
15. Good grasping power and attention to detail: breadth, depth, clarity, accuracy, preciseness, specificity, relevance, significance, completeness, consistency.
16. Imagination: storyboarding, extrapolation, visualization, cognitive flexibly: ability to transfer and models of solutions of one situation/field to another, multi-perspective thinking, lateral thinking, inductive thinking, out-of-box thinking, unstructured thinking, creativity and idea initiation, and innovation.
17. Knowledge of contemporary issues and business practices.
18. Knowledge of physical and natural world. Intercultural knowledge.
19. Mentoring, coaching, and training skills.
20. Organizational skills.
21. Persuasion, negotiation, consensus building, and conflict resolution skills.
22. Problem orientation, problem definition and formulation, generations of alternatives. Ability to convert ill-defined problematic situations into software solvable problem. Ability of infusing different thinking patterns developed through their experience in other domains. Inclination for reuse and synthesis by integration. Emphasis on elegant and simple solutions.
23. Problem solving skills: solution implementation and verification.
24. Project planning and management, project scoping, estimation, process planning and management,
25. Quality, cost, and security consciousness, pursuit of excellence, intellectual accountability and responsibility, intellectual integrity, intellectual courage, strength of conviction: assertive without being aggressive. Commitment to systematic documentation of the work. Recognize and act upon the need to consult other experts, especially in matters outside their area of competence and experience. Commitment to the fulfillment of needs of all users and persons who get affected by the technological solutions. Eagerness and inclination to understand the unintended consequences of creating software inappropriate or at odds to its real purposes. Commitment to health, safety, dignity, and welfare of the users and also the people who will be affected by their systems. Sensitivity towards constraints like economic disadvantage and physical disabilities that may limit software accessibility.
26. Reasoning: quantitative and verbal, and critical thinking: ability to question, validate, and correct the purpose, problem, assumptions, perspectives, methods, evidence, inference, reliability, relevance, criteria, and consequences. Numerical ability.
27. Reflection and transition between ladders of reflection. Meta-cognition.
28. Research skills: methods of mathematical research, engineering research, design research, and social science research.
29. Self-acceptance, self-regulation, self-awareness, self-improvement: strength to resist instant gratification in order to achieve better results tomorrow. Being honest and forthright about one’s own limitations of competence. Tendency to avoid false, speculative, vacuous, deceptive, misleading, or doubtful claims. Faith in reason and review, inclination for verification and validation, respect for facts and data. Awareness and regulation of automatic thoughts.
30. Systems-level perspective, ‘big picture’ view, holistic and multi-perspective thinking, knowledge integration, consideration for multilateral viewpoint, and user-centeredness. Process and rule-oriented mindset. Tolerance to ambiguity and risk. Ability to understand and also build upon other’s work. Ability to work such that others can easily understand and build upon.
31. Technical competence to solve the software solvable problems using tools and techniques, Use of open source software. Knowledge of industry’s best practices and standards, appreciation of what is technically feasible. Identify the risk level of each piece of work.
32. Wealth creation skills.
33. Work load management.
E questo è tutto? Non so, poteri di levitazione o di bilocazione? Saper risolvere a memoria sistemi di equazioni integro-differenziali alle derivate parziali? Falegnameria? Teoria del disegno artistico?
lunedì 28 marzo 2011
Tagliare i costi per l'innovazione può far fiorire il FLOSS
Il FLOSS può essere scaricabile gratuitamente, ma si tratta comunque di software e come nel caso di quello proprietario ha dei costi che qualcuno deve sostenere. Questa frase non è l’ultima sparata di Steve Ballmer, Larry Ellison o qualche altro personaggio di quella risma, ma un’affermazione di Neil Levine di Canonical.
Ovviamente con quelle parole non aveva intenzione di nascondere i vantaggi che il FLOSS ha sulle alternative proprietarie, ma di quello che serve affinché un progetto raggiunga le sue piene potenzialità portando contemporaneamente ad un risparmio economico ed una trasformazione del mercato.
La critica che fa Levine è che molti business legati al FLOSS finiscono per diventare un po’ troppo simili ai loro concorrenti proprietari e, quindi, si finisce per pagare, più o meno evidentemente, una licenza per ogni computer. Facendo un esempio pratico perché essere obbligati a pagare per il supporto sui server di sviluppo quando il personale presente è in grado di gestirlo autonomamente ed avrebbe bisogno solamente di un supporto rapido per i problemi sui server business critical?
Secondo Levine il FLOSS avrebbe dovuto spezzare le barriere che c’erano sul mercato e far andare in bancarotta vecchi giganti come Microsoft ed Oracle grazie alla sua velocità di sviluppo e possibilità di personalizzazione. Purtroppo si è vinto qualche battaglia, ma la guerra non è stata un successo. Come possiamo notare attorno a noi Linux è in utilizzato in moltissimi ambienti eterogenei, ma il FLOSS sul desktop è ben lontano dalla dominazione. Si vede in giro, ma non ha ancora sviluppato un’importante ecosistema al di fuori dei sistemi operativi liberi.
Per ottenere veramente il massimo le aziende dovrebbero ripensare le logiche di business ed aggredire il mercato portandolo nella direzione che più le avvantaggia. Ricapitolando, il valore sta nel servizio e nel supporto che viene offerto ed il software è solo un mezzo per ottenere questi risultati. Levine vorrebbe che si pensasse al software in maniera diversa dal passato, ponendo l’accento non sul costo di gestione di un software, ma del costo per ottenere un’innovazione. Un software proprietario è una barriera per lo sviluppo, mentre uno libero può più facilmente adattarsi per aiutare a sviluppare un nuovo business.
Proviamo a fare un esempio. Se serve una certa quantità di denaro per ogni macchina su cui far girare un servizio, si può facilmente arrivare a dei costi notevoli anche per un solo prototipo. Il costo del software diventa quindi un ostacolo allo sviluppo. Se invece si può testare e validare facilmente il prototipo di un servizio sarà poi più facile ottenere l’autorizzazione per un contratto di supporto e/o servizi. Un po’ quello che sta cercando di fare Canonical con Ubuntu.
Via | TheRegister
Tagliare i costi per l'innovazione può far fiorire il FLOSS é stato pubblicato su ossblog alle 17:00 di mercoledì 23 marzo 2011."
giovedì 10 marzo 2011
Software batte hardware
giovedì 20 gennaio 2011
Le applicazioni in Qt di Nokia sono già il presente per Ubuntu 11.04
In un intervento piuttosto contestato, alla vigilia dell’Ubuntu Developer Summit (UDS) dedicato a Natty Narwhal, si parlava dell’opportunità di un futuro su Ubuntu per le librerie Qt. L’ipotesi era stata avanzata da Matt Zimmerman, CTO di Canonical, e possiamo dire che le indiscrezioni hanno avuto più di una conferma. Non è solo Unity 2D, ma è soprattutto Mark Shuttleworth che ha annunciato la convergenza.
La formula scelta da Canonical per ampliare lo spazio dedicato alle applicazioni in Qt è un po’ diversa da ciò che ci si sarebbe aspettati. Perché il focus di Ubuntu per Qt rimane GNOME, anziché – come avrebbe avuto più senso – KDE e Kubuntu. Nessuna polemica sulle Gtk+ (benché con Unity i motivi di scontro si sprechino), ma un’opportunità d’apertura a backend diversi da quelli predefiniti per l’utilizzo su GNOME 2/3.
Eppure, per quanto resti remota, l’ipotesi di avere Kubuntu con Unity non è così improbabile. Unity 2D è già in Qt per GNOME e aggiungere un completo supporto al compositing di OpenGL non sarebbe un lavoro immane. A ciò s’aggiunga che Firefox avrà in futuro una versione scritta in Qt, che avvicinerebbe ulteriormente Ubuntu e Kubuntu. Escluso il desktop con Plasma, KDE non perderebbe le sue caratteristiche.
Via | Mark Shuttleworth
Le applicazioni in Qt di Nokia sono già il presente per Ubuntu 11.04 é stato pubblicato su ossblog alle 09:00 di mercoledì 19 gennaio 2011
giovedì 6 gennaio 2011
It's official: Windows 8 will run on ARM
giovedì 30 dicembre 2010
La cattedrale e il bazaar
Quella che segue è la mia analisi di un progetto open source di successo, fetchmail, deliberatamente utilizzato come test specifico per la verifica di alcune sorprendenti teorie sullo sviluppo del software suggerite dalla storia di Linux. Le mie argomentazioni su tali teorie mettono a confronto due diversi stili di sviluppo, il modello “cattedrale” in voga in gran parte del mondo commerciale, opposto al modello “bazaar” del mondo Linux. Da qui passo poi a dimostrare come tali modelli derivino da premesse divergenti sulla natura dell'attività di debugging del software. Arrivo quindi a stabilire la validità dell'esperienza di Linux riguardo l'affermazione “Con molti occhi puntati addosso, ogni bug diventa una bazzecola”, per suggerire analogie produttive con altri sistemi di agenti indipendenti in grado di auto-correggersi, concludendo infine con una serie di riflessioni sulle implicazioni di queste analisi per il futuro del software.
mercoledì 15 dicembre 2010
Stallman: Chrome OS e' roba da stupidi
venerdì 10 settembre 2010
Apple e gli sviluppatori liberati
domenica 29 agosto 2010
GLibC è free software: Oracle ha aperto la Sun RPC
L’ultima parte di codice protetto dalla Sun RPC è stata “liberata” da Oracle e GLibC è finalmente free software al 100%. Non tutto il male viene per nuocere, parrebbe: un limite risalente al 1985 è stato risolto solo con l’acquisizione di Sun Microsystems da parte di Oracle. Una delle librerie fondamentali per Linux è diventata FLOSS a venticinque anni dal suo concepimento. È rilasciata sotto la nuova licenza BSD.
Il problema è che, quando la licenza per GLibC è stata concepita nel 1984, non esisteva ancora il concetto di free software come siamo abituati a intenderlo con la FSF e la GPL. Per quanto possa sembrare paradossale, la Sun RPC per l’epoca era già una licenza molto permissiva. Il processo d’apertura ha richiesto tanto tempo perché la soluzione migliore è apparsa quella di ridistribuire il codice con una licenza diversa.
Sun Microsystems non ha mai risolto il conflitto, forse persino per incuria. Alcuni tentativi per ripristinare una sorta d’omogeneità sulle licenze di distribuzione per i componenti di GLibC erano stati fatti nel 2009, ma soltanto oggi è stato possibile intervenire. Ed è stato grazie a Oracle. Tom Callaway ha dato la notizia sul suo blog e il codice è sui server di Red Hat. Restano da appianare solo alcune questioni su krb5.
Via | The H Open
Google Chrome 7 Gets GPU Acceleration for 2D and 3D Content
The latest Chromium builds can now send some of the renderin... (read more)"
giovedì 19 agosto 2010
Firefox Beta 4, 5, 6, 7 Coming, and All Betas Are Equal
In fact, as Mozilla’s Director of Firefox noted earlier this year, multiple Betas of Firefox 4.0 will be delivered, at a rate of once every couple of week or so.
<... (read more)"
lunedì 5 aprile 2010
Bliki: VcsSurvey
When I discussed VersionControlTools I said that it
was an unscientific agglomeration of opinion. As I was doing it I
realized that I could add some spurious but mesmerizing numbers to
my analysis by doing a survey. Google's spreadsheet makes the
mechanics of conducting a survey really simple, so I couldn't
resist.
I conducted the survey from February 23 2010 until March 3 2010
on the ThoughtWorks software development mailing list. I got 99
replies. In the survey I asked everyone to rate a number of version
control tools using the following options:
- Best in Class: Either the best VCS or equal best
- OK: Not the best, but you're OK with it.
- Problematic: You would argue that the team really ought to be using something else
- Dangerous: This tool is really bad and ThoughtWorks should press hard to have it changed
- No opinion: You haven't used it
The results were this:
| Tool | Best | OK | Problematic | Dangerous | No Opinion | Active Responses | Approval % |
|---|---|---|---|---|---|---|---|
| Subversion | 20 | 72 | 6 | 1 | 0 | 99 | 93% |
| git | 65 | 19 | 1 | 0 | 14 | 85 | 99% |
| Mercurial | 33 | 27 | 2 | 0 | 36 | 62 | 97% |
| ClearCase | 0 | 3 | 14 | 41 | 41 | 58 | 5% |
| TFS | 0 | 0 | 32 | 22 | 44 | 54 | 0% |
| CVS | 0 | 14 | 59 | 11 | 15 | 84 | 17% |
| Bazaar | 1 | 13 | 3 | 0 | 80 | 17 | 82% |
| Perforce | 1 | 26 | 16 | 1 | 54 | 44 | 61% |
| VSS | 1 | 1 | 11 | 64 | 22 | 77 | 3% |
As well as the raw summary values, I've added two calculated
columns here to help summarize the results.
- Active Responses: The total of responses excluding 'No
Opinion'. (eg for git: 65 + 19 + 1 + 0) - Approval %: The sum of best and ok responses divided by active
responses, expressed as a percentage. (eg for git: (65 + 19) / 85)
The graph shows a scatter plot of approval percentage and active
responses. As you can see there's a clear cluster around Subversion,
git, and Mercurial with high approval and a large amount of
responses. It's also clear that there's a big divide in approval between those
three, together with Bazaar and Perforce, versus the rest.
Although the graph captures the headline information well, there's
a couple of other subtleties I should mention.
- Although the trio of Subversion, git, and Mercurial cluster close
together on approval, git does get a notably higher amount of best
scores: (65 versus 20 and 33). - VSS got the most 'dangerous' responses, but a couple of people
approved of it. - Neither TFS or ClearCase are liked much, but ClearCase got more
'dangerous' responses than TFS (41 versus 22). - Don't read too much into small differences as I'm sure they aren't
significant. I'm sure the difference in approval percentage between VSS, TFS,
and ClearCase isn't signifcant, but the difference between these three
and the leaders is.
Some caveats. This is a survey of opinion of ThoughtWorkers who
follow our internal software development discussion list, nothing more. It's
possible some of them may have been biased by my previous article
(although unlikely, since I've never managed to get my ThoughtBot
opinion-control software to work reliably). Opinions of tools are
often colored by processes that are more about the organization than
the tool itself. But despite these, I think it's an interesting data
point.
I should also stress the important point to take away from this
isn't the comparison between those close in the numbers, eg comparing
git and Mercurial or comparing TFS and ClearCase. Any survey like this
has a certain amount of noise in it, and I suspect the noise here is
greater than such a difference. The important point is the big
approval gap between the leading tools (Subversion, git, and
Mercurial) and the laggards - essentially the point in
VersionControlTools.
Continuous Integration
sabato 3 aprile 2010
Efficient C Tip #11 - Avoid passing parameters by using more small functions
- Passing parameters to functions is costly.
- Conditional branch instructions can be very costly on CPUs that have instruction caches (even with branch prediction).
I don't think that too many people will disagree with me on the above. Despite this I too often see a style of coding that incurs these costs unnecessarily. I think it's best illustrated by a (real world) example. The issue is one that will be familiar to most of you. An embedded system contains a number of discrete LEDs (say 3), and the requirement is to write some code to allow higher level code to either turn on, turn off, or toggle a particular LED. The way I often see this coded is as follows:
typedef enum
{
LED1, LED2, LED3
} LED_NO;
typedef enum
{
LED_OFF, LED_ON, LED_TOGGLE
} LED_ACTION;
void led(LED_NO led_no, LED_ACTION led_action)
{
switch (led_no)
{
case LED1:
switch (led_action)
{
case LED_OFF:
PORTB_PORTB0 = 0;
break;
case LED_ON:
PORTB_PORTB0 = 1;
break;
case LED_TOGGLE:
PORTB_PORTB0 ^= 1;
break;
default:
break;
}
break;
case LED2:
...
}
So what's wrong with this you ask? Well in a nutshell the parameters passed to the function are used strictly to control the order of execution. There is no code common to any pair or group of parameters. When faced with a situation such as this, I instead implement the code as a large number of very small functions. For example:
void led1_Off(void)
{
PORTB_PORTB1 = 0;
}
void led1_On(void)
{
PORTB_PORTB1 = 1;
}
void led1_Toggle(void)
{
PORTB_PORTB1 ^= 1;
}
...
Let's compare the two approaches.
Efficiency
This blog posting is supposedly about efficiency, so let's start with the results. I coded these two approaches up together with a main() function that exercised all 9 possible combination's. I then turned full speed optimization on and looked at the results for an AVR processor.
Single function approach: 78 bytes for main(), 94 bytes for the LED code. Execution time 208 cycles.
Multiple function approach: 42 bytes for main(), 54 bytes for the LED code. Execution time 96 cycles.
Clearly my approach is significantly more efficient.
Usability
By usability I'm referring to the case where someone else needs to use your code. They know they need to say toggle LED2 so they hunt around and find the file led.h. The question is, once they have opened up led.h, how quickly can they determine what they have to do in order to toggle LED2? In the single function case they are presented with just one function (which is a plus), but then they have to locate the enumerations and work out the parameters that need to be passed to the function (which is a minus). In the multiple function case, they have to search through a list of functions looking for the correct one. However once they have found it, it's very clear what the function does.
For me, I think it is a toss up between the two approaches as to which is more usable.
Maintainability
In this case the multiple function approach is the big winner. To see how this is, consider what happens to the single function case when one adds an LED or adds an action. The single function case just explodes in size, whereas with the multi-function approach one simply adds more very simple functions.
Conclusions
If you buy my analysis then clearly the multi-function approach is superior in both efficiency and maintainability - two areas that are dear to my heart. Now granted this is a fairly extreme example. However in my experience if you look through a reasonable amount of code you will soon discover a function that essentially does one thing or another based upon a function parameter. When you locate such a function you might want to try breaking it into two functions in the manner described here - I think you'll be pleased with the results. Previous Tip
****
As the readership of this blog has grown I must say I have been really impressed with the many insightful comments that have been posted. I know I learn a lot from them, and so I suspect, do a lot of the other readers. Thus for those of you that have commented in the past - thank you. For those of you yet to post a comment, I encourage you to take the plunge!
Home"
Firmware-Specific Bug #4: Stack Overflow
Unfortunately, stack overflow afflicts embedded systems far more often than it does desktop computers. This is for several reasons, including:
- embedded systems usually have to get by on a smaller amount of RAM;
- there is typically no virtual memory to fall back on (because there is no disk);
- firmware designs based on RTOS tasks utilize multiple stacks (one per task), each of which must be sized sufficiently to ensure against unique worst-case stack depth;
- and interrupt handlers may try to use those same stacks.
Further complicating this issue, there is no amount of testing that can ensure that a particular stack is sufficiently large. You can test your system under all sorts of loading conditions but you can only test it for so long. A stack overflow that only occurs “once in a blue moon” may not be witnessed by tests that run for only “half a blue moon.” Demonstrating that a stack overflow will never occur can, under algorithmic limitations (such as no recursion), be done with a top down analysis of the control flow of the code. But a top down analysis will need to be redone every time the code is changed.
Best Practice: On startup, paint an unlikely memory pattern throughout the stack(s). (I like to use hex
23 3D 3D 23, which looks like a fence ‘#==#’ in an ASCII memory dump.) At runtime, have a supervisor task periodically check that none of the paint above some pre-established high water mark has been changed. If something is found to be amiss with a stack, log the specific error (e.g., which stack and how high the flood) in non-volatile memory and do something safe for users of the product (e.g., controlled shut down or reset) before a true overflow can occur. This is a nice additional safety feature to add to the watchdog task.Firmware-Specific Bug #3
Firmware-Specific Bug #5 (coming soon)"
Effective C Tip #8 - Structure Comparison
To see why this argument is advanced, one must understand that a compiler is free to place pad bytes between members of a structure so as produce more favorable alignment of the data in memory. Furthermore, the compiler is not obligated to initialize these pad bytes to any particular value. This code fragment illustrates the problem:
uint8_t x;
uint8_t pad1; /* Compiler added padding */
uint8_t y;
uint8_t pad2; /* Compiler added padding */
void foo(void)
{
COORD p1 p2;
p1.x = p2.x = 3;
p1.y = p2.y = 4;
/* Note pad bytes are not initialized */
if (memcmp(&p1, &p2, sizeof(p1)) != 0)
{
/* We may get here */
}
...
}
void foo(void)
{
COORD p1 p2;
p1.x = p2.x = 3;
p1.y = p2.y = 4;
if (!are_equal(&p1, &p2))
{
/* We should never get here */
}
...
}
Now consider what happens if I add a third member z to the COORD structure. My structure definition and function foo() become:
uint8_t x;
uint8_t pad1; /* Compiler added padding */
uint8_t y;
uint8_t pad2; /* Compiler added padding */
uint8_t z;
uint8_t pad3; /* Compiler added padding */
void foo(void)
{
COORD p1 p2;
p1.x = p2.x = 3;
p1.y = p2.y = 4;
p1.z = 6;
p2.z = 5;
if (!are_equal(&p1, &p2)
{
/* We will not get here */
}
...
}
The problem is that I now have to remember to also update the comparison function. Now clearly in a simple case like this, it isn't a big deal. However, in the real world where you might have a 500 line file, with the comparison function buried miles away from the structure declaration, it is way too easy to forget to update the comparison function. The compiler is of no help. Furthermore it's my experience that all too often these sorts of problems can exist for a long time before they are caught. Thus the bottom line, is that member by member comparison has its own set of problems.
So what do I suggest? Well, I think the following is a reasonable approach:
- If there is no way that your structure can change (presumably because of outside constraints such as hardware), then use a member by member comparison.
- If you are working on a system where structure members are aligned on byte boundaries (which is true to the best of my knowledge for all 8 bit processors, and also most 16 bit processors), then use memcmp(). However, you need to think about doing this very carefully if there is the possibility of the code being ported to a platform where alignment is not on an 8 bit boundary.
- If you are working on a system that aligns on a non 8 bit boundary, then you must either use member by member comparison, or take steps to ensure that all the bytes of a structure are initialized using memset() before you start assigning values to the actual members. If you do this, then you can probably use memcmp() with a reasonable amount of confidence.
- If speed is a priority, then clearly memcmp() is the way to go. Just make sure you aren't going to fall into a pothole as you blaze down the road.
If you use the memcmp() approach you are checking for bit equality rather than value equality. Now most of the time they are the same. Sometimes however, they are not. To illustrate this, consider a structure that contains a parameter that is a boolean. If in one structure the parameter has a value of 1, and in the other structure it has a value of 2, then clearly they differ at the bit level, but are essentially the same at a value level. What should you do in this case? Well clearly it's implementation dependent. It does however illustrate the perils of structure comparison.
Finally I should mention issues associated with structures that contain pointers. CS guys like to distinguish between deep and shallow structure comparison. I rarely write code where a deep comparison is required, and so for me it's mostly a non-issue.
Previous Tip
Home"