Why Pascal is better than C

Or to be more specific, why is C bad.

I learnt Pascal before C, and Delphi before C++. So this might be just that. Meaning that my brain is damaged by Pascal 🙂

I’m also Hungarian and the sentence and phrase construction order is different than in English. And because you express your thoughts in language, it pretty much means that we learn to think in different order than humanoids brought up learning English. The order in Hungarian is from big to small. In addresses (country, city, street, number), time (year, month, day, hour, minute, seconds…), names (family name, given name), even in articles (what we want to discuss, and then the details), someone’s stuff rather then stuff of someone.
So this might also contribute to my insanity. What seems to me logical order, might be different for others.

So, Why is C driving me crazy?

There is a lot of reason for it, but for now just look at a simple example.
Lets move some memory around.

When I thing about moving, I think of “Let’s move this to somewhere”. (this, to)
And I would think when a messenger gets a delivery task to carry something, form somewhere, to somewhere that would be the order (form , to).
If I know “where from” then I can already start going that way to pick it up. That is how taxis work, they first only know where to pick up someone. That is also how the IP header is structured (Source IP Address, Destination IP Address).
It feels natural: from somewhere, to somewhere.

So when I want to move some bytes in the memory I would specify from where, to where, and how much.

And that is how Move in Pascal does it:
procedure Move ( const SourcePointer; var DestinationPointer; CopyCount : Integer ) ;

On the other hand memmove in C uses the opposite order.
void * memmove ( void * destination, const void * source, size_t num );
This just doesn’t feel right.

(Both can handle overlapping source, destination buffers, that’s why they are move and not copy.)

When you write in command line you also use source destination order (copy, cp, move, mv) [1]
PHP uses from, to order too. [2]
C#, .NET also uses source, destination order. [3]

You can find the same reversal in source and destination operand ordering in AT&T and Intel assembly formats.
Intel has dest = source order, while AT&T the opposite.
(It’s strange, I’m compelled to end my lines with a semicolon;)

Example: [4]

Intex Syntax AT&T Syntax
mov eax,[ebx]
mov eax,[ebx+3]
add eax, 4
movl (%ebx),%eax
movl 3(%ebx),%eax
addl $4, %eax

I like Intel’s syntax more. Because it resembles the assignment operator order:
eax = *ebx;
eax = *(ebx+3);
eax += 4;

And I know that it is the opposite order (dest, source) of Move, but I’m crazy like that…
But mov actually means: make this equal to that, (there is no actual moving from).

I think the order should always be this, that and here, there.
So if I call a function Move, than it should move from here to there.
But if I call a function MoveTo, then it might move to here from there.
(We could clarify by naming it MoveFrom or MoveFromTo (which sound awful), but the from, to order just seems natural to me.)

Next time I might write something about constructors. Till then you can also read my rant about arrays, and why are they suck in C, and rock in Pascal… 😉

Python

I wanted to look into some Python development, because it seemed a cool (productive) language.
I have seen some python code before, but have not coded much (if any).

So yesterday I installed an IDE for it, and today wrote a (simple) calculator. This included installing the environment (and watching StarCraft 2 DreamHack Open : ) .
Here is the code,
and a readme for it.

dynamic arrays and the lack of them in C

I love Pascal and Delphi. In particular I love its memory management.
I can use string, array of byte types. They are both dynamic arrays. They are not just pointers to a memory region, they have a size or Length (how Delphi calls them).
The great thing about them is that they can be re-sized. But an other great thing is that you can check their sizes no matter what (if you forgot to remember them, or if you receive them as argument of a function/procedure/method).
SetLength()
Length()
Low()
High()
Open array parameters
^^^^ This is what I need in C!

In C it’s like they want to hide this information from you. First, there is no such thing as dynamic array in C (there are only pointers). There are arrays in C++ (but I read that you should avoid them at all cost, and use vector instead), but also you cannot re-size them, so they are not fixed length, but not really dynamic either.
So how can you get the length of an array or memory region?
common methods:
In C you can use #define lengthof(array) (sizeof(array)/sizeof(array[0])) if it’s a fixed length array, but you cannot use it on function arguments, or pointers…

There is a clever template (if you write it) in C++
template
inline unsigned int length( T(&a)[N] ) { return N; }
that can be used to determine length of arrays.

So where are the real dynamic, realizable arrays, and how to implement them?
If you want to allocate memory run-time (and re-size them) you can use malloc() (realloc() and free())
That’s all fine until you want to get the size of them. Which can happen if you allocate the memory outside of a function where you want to use it. There is no std libc function to get the (malloc) allocated memory size which is kept somewhere (so free() can free it, realloc can re-size it and available memory regions can be kept track of). There is however a GNU extension malloc_usable_size() which I, we desperately need (even if we didn’t know it).
.. Well we need an array whose size we can check no matter if it’s dynamic or static, but…
Also note that malloc_usable_size does NOT actually return the requested size, but the allocated one (due to alignment, minimum block size), but at least we can use it for asserts.
So we still need to keep track of array sizes separately (extra variables, extra arguments) and risk messing them up…
(or rewrite everything to use structures of size, pointer pairs)

Another topic is multidimensional (dynamic) arrays (not just arrays of arrays)…

Note: This actually I have written just now 🙂 See I do not just reuse ages old materials:)

Hungarian notation

Hungarian notation is usually miss-interpreted as the notation of declared type of variable. This is not the case. So when I read a book that says that Hungarian notation is useless in type safe languages, I feel bad. 🙁

Hungarian notation is supposed to indicate semantic type (type of content, meaning) and not syntactical type (type of variable). The compiler knows how to handle (read, write, do operations with) variables, but it has no idea what they are, what they mean. And if you are not naming your variables right you might not either.

Lets say you are writing some physics calculation. You are probably do not want to add mass with length or acceleration… (you might want to multiply, divide them but not add, subtract). To the compiler (even the most type safe ones) they are all just floating point numbers (or doubles, extendeds). And if you are naming your variables like marias_speed, peter_is_this_fast, velocity_of_kevin, then you are looking for trouble. It’s harder to notice the error in this: marias_speed + peter_is_this_fast + mass_of_kevin, than in this: veMaria + vePeter + maKevin. In this case Hungarian notation could mean units of measurement.
The same goes if you are calculating screen position in pixels, inches, centimeters…

The more common task a programmer has to deal with is user input. User input is always unsafe! An SQL string is (or should be) treated differently than user input, or html text… strings need to be escaped differently for different output. So it might be advantageous to include in the variable name if it’s unsafe, html-safe, sql-safe …
Also use printf(“%s”,usStr) rather than printf(usStr) 🙂

Note: I found this old draft from 2012 January. Another one again… I shouldn’t misplace these 🙂

USB Mouse Raw Data

A Fujitsu-Siemens Wireless egeremhez nincs 64 bites windows driver. Az alap dolgok persze e nélkül is mennek, de van rajta néhány gomb, amit az OS nem ismer fel.

Probáltam libusb-win32-vel kinyerni az adatokat, ami csak többé kevésbé volt sikeres. A filter funkciót használtam.
Egyik egérnél csak a forgalom egy részét kapta el, elég sok csomag elkerülte. A Fujitsu-Siemens egérnél ugyan elkapott minden csomagot, de ezzel együtt le is választotta az op-rendszerről (a mutató mozgásra és kattintásra nem reagált).

Az egyik fórumon olvastam a GetRawInputData Win API függvényt. Eltartott egy ideig, de sikerült beüzemelni, viszont ez meg csak azokat az adatokat továbbítja, amit a windows egyébként is kezel.

Nem valószínű hogy most nekiállok windows drivert írni az egeremhez, de lehet hogy majd egyszer…

Tray Timer

Összeraktam egy kis időzítő programot ma. Ez nem ébresztő óra, arra ott van az outlook, lightning (thunderbird), vagy akár a google online naptára. (Meg még vagy ezer maásik program).
Ez arra jó, ha gyorsan be akarjuk állítani, hogy pl. 10 perc mulva jelezzen (hogy megfőtt a kemény tojás).
Gyorsan és egyszerűen egérrel, vagy billentyűzettel be tudjuk állítani, lehet hang jelzéssel, vagy a nélkül, egyszerre akár több (korlátlan) időzítőt is elindíthatunk, lehet utána törölni a feleslegeseket.

Még kicsit félkész, de már jól használható.

FSTrayTimer_bin_20110201
FSTrayTimer_src_20110201

Delphi szálak, üzenetek…

Néhány hasznos dolog Delphi programozóknak ami eddig kimaradt.

Még régebben találtam egy jo kis magyar leírást a többszálúságról pontosabban annak elkerüléséről Delphiben, miközben a felhasználói felletet nem akadályozva akarunk hosszabb ideig tartó műveleteket végezni.
szálőrület bejegyzései: TThread, Application.ProcessMessages, PeekMessage, OnIdle

A Windows üzenetkezeléséről Delphiben egy másik hasznos leírás a A Key’s Odyssey

Dynamic array, open array parameters, array of const @ Rudy’s Delphi Corner – Open array parameters

Debugging with OutputDebugString() @ Delphi Tips – Delphi Programming

Persze még van sok minden de most ezek jutottak eszembe.