January 2012

Warning! Some information on this page is older than 5 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

# Visual C++ is so Liberal

Jan 2012

Here is an issue in C++ code I've came across some time ago and recently I've found again in some other code. This code is invalid according to language standard, still it compiles in Visual C++/Visual Studio and works correctly. Can you see what's wrong with it?

class Class1
    int m_Number;
    Class1( int number ) : m_Number( number ) { }

void Function1( Class1& obj1 )
    obj1.m_Number = 2;

int main()
    Function1( Class1( 1 ) );

The problem is that we pass a temporary object of Class1 to the Function1, while this function takes object by reference, not by reference to const. Such R-value shouldn't be converted to non-const reference, or else we could modify the temporary object - which we actually do inside the function.

Visual C++ 2008 and 2010 with default project options compiles this without any warning. Setting Warning Level to 4 (/W4) generates a warning:

warning C4239: nonstandard extension used : 'argument' : conversion from 'Class1' to 'Class1 &'

Using Disable Language Extensions (/Za) makes it an error:

error C2664: 'Function1' : cannot convert parameter 1 from 'Class1' to 'Class1 &' A non-const reference may only be bound to an lvalue

It means we are dealing with a nonstandard Microsoft extension here. GCC refuses to compile this code, even with standard options:

error: invalid initialization of non-const reference of type 'Class1&' from an rvalue of type 'Class1' error: in passing argument 1 of 'void Function1(Class1&)'

Another story: Today I've learned that C++ standard doesn't have forward declarations of enums. I used it for long time and now I know it's another nonstandard Microsoft extension.

My conclusion is that programming in C++ using Visual C++ is like programming in DirectX using NVIDIA graphics cards: the platform is so liberal that your code may work even if you do something invalid. It also means that to use portable libraries instead of WinAPI is not enought to write code portable from Windows to Linux and other platform. You should also check if your code is accepted by other compilers. Increasing warning level in project options can also help with that, just like using Debug Version of Direct3D in DiectX Control Panel and observing debugger Output to find possible problems in calls to Direct3D API. It's better to ensure early that your code is valid instead of later complain that alternative (GCC) compiler or alternative (AMD) GPU driver causes problems.

On the other hand I believe that platform independence and strict C++ standard correctness is not a great value in itself. If you know your code is supposed to just work under Windows and be compiled in Visual C++, why not make use of available extensions and rely on specific compiler behavior? It can be convenient, while maintaining code that have to work with different compilers and platforms is a lot of additional work, possibly unnecesary.

Comments | #c++ #visual studio Share

# Improved RSS Feed

Jan 2012

I improved the script for generating news feed for my website. It now shows entire contents of my blog posts, including HTML formatting. So if you visit my blog sometimes and haven't done it yet, subscribe to my...

RSS Feed: Adam Sawicki - Homepage (Blog) RSS Feed

using some desktop or online reader, like the popular Google Reader. I use this one for some time and I like it a lot. RSS/Atom is really good technology. With it you can see unread updates from dozens of your favourite blogs in a single place and read them all without actually visiting the website.

Comments | #homepage #webdev #web Share

# New Colors

Jan 2012

As you can see, I changed colors of my website. New new colors scheme is based on Solarized palette, which claims to be carefully designed to have some good properties. How do you like it?

EDIT: OK, you are right. That colors looked bad. But I will leave rounded corners from that new stylesheet :)

Comments | #homepage Share

# Unusual RAII from LibVLC

Jan 2012

RAII (Resource Acquisition Is Intialization) is a programming technique recommended in C++ for managing and freeing all kinds of resources, like allocated memory or opened files. It involves creating on the stack (by value) an object of some class that will automatically free contained resources in its destructor, at the end of the scope. That's how smart pointers work. Using it is not only needed for exception safety. It generally helps not to forget about freeing resources, like when doing return or break in the middle of the code, as well as not to duplicate this freeing code.

When working with LibVLC library, I've spotted an interesting RAII-like pattern in its source code. It is based on a local structure inside a function, which holds resources and frees in its destructor these resources that are already acquired - like this:

bool DoLotsOfStuff()
    struct Resources
        int* array;
        FILE* file;

            if( file )
                fclose( file );
            if( array )
                delete[] array;
    } resources = { 0 };

    // Do some startup...

    if( CheckSomeError() )
        return false;

    resources.array = new int[1024];

    // Do some work...

    if( CheckSomeError() )
        return false;

    resources.file = fopen( fileName, "rb" );
    if( resources.file == NULL )
        return false;

    // Do some more work...

    if( CheckSomeError() )
        return false;

    // array is freed and file is closed no matter if control reached here or returned earlier.
    return true;

Comments | #c++ Share

# Why do I Publish Source Code?

Jan 2012

I like Open Source. Not in the way that some like Linux and hate Windows, but I just believe that to read or use a piece of code is often more helpful than to read only an abstract description of some algorithm. That's why I publish source of my personal projects. I can see many passionate programmers - like these from Warsztat - are not so enthusiastic to disclosing their sources. I was wondering why and here I'd like to share my thoughts on this subject, in hope I convince some of you to make your personal projects Open Source :)

First, I can hear an argument sometimes telling that you are ashamed of showing your code because you think it is bad. My answer to this can only be: you are probably wrong. Do you really believe that the "professional", "commercial" code inside companies - which is usually evolving for years, maintained by many people, modified to reflect constantly chaging requirements and written in a rush - is better than yours? Not necessarily. Or maybe you think that your code would be better if you put lots of additional comments in it, code in more object-oriented fashion or use more design patterns? Again, I don't think so.

You may also be afraid that someone looks at your code and tells that you are a beginner? Well, you may be right but... what's wrong with that? You code shows the level of your skill in programming and you shouldn't avoid showing who you really are. Remember that on the Internet there is always more beginner programmers who can learn from you than the advanced ones that could potentially make fun of your code. If you are afraid of headhunters searching the Internet, please keep in mind that when applying for a job, you may be asked to send samples of your code anyway - just as I was.

Second argument I can hear is: "But it's just my project, I don't want to make it Free Software developed by the community like Linux". That's a stereotype. Opening your sources doesn't mean the project cannot be developed by only you and will automatically be modified by some others programmers. Such thinking is just like when I hear somebody telling that programming in C++ means you extensively use OOP, while never use global variables, macros or printf. I've never received an email with a patch or other proposal for particular change in my code or collaboration in developing of my project. Even for my projects that are GNU GPL, I only get suggestions that I should add or modify some features.

If so, is it worth publishing source code anyway? My practice clearly answers yes, but not to start a community open source project. I sometimes receive emails asking about a piece of code for an algorithm I've decribed on my webpage, but I didn't provide code for. Programmers from around the world are constantly challenged with tasks they haven't done before, whether at work or at university. Their problems can be similar to yours. They Google for solutions. Your small niche place in the Web or a post on the forum can be of great help for such people.

Comments | #philosophy Share

# The Concept of Wait Cursor

Jan 2012

When coding a GUI application, sometimes we have to conduct lengthy operation like loading or saving a file. It would be perfect if every such operation was done on separate, background thread while main thread - the one responsible for windowed interface - would show progress and allow to cancel the operation at any time. But multithreaded programming is hard, so some (not so critical and not so long) operations, like loading a configuration file, are usually done on the main thread, freezing the whole GUI. It's OK as long as the operation takes no longer than a fraction of second or several seconds - just like loading and parsing small configuration file, unless the file is located on a floppy disk :)

But it's good to show to the user that some operation is being performed so he doesn't get angry and terminate your application so quickly. Changing mouse cursor from "Normal" to "Wait" is useful here, so GUI libraries provide functionality for this.

In C#, we do it by setting Cursor property of a Form. Assuming we are inside a method of a Form:

Cursor = Cursors.WaitCursor;
// Lengthy process...
Cursor = Cursors.Default;

Just don't forget to restore default cursor no matter what's the result of the operation. try-finally section can be useful here to make the wait cursor "exception-safe". Good news is that if you wish to show a MessageBox informing user about an error that happened between setting the cursor to WaitCursor and restoring it, the cursor will change to Default automatically for the time the message window is shown.

It may be tempting to use Application.UseWaitCursor instead, but this method is worse. It requires to go back to main message loop before the cursor change takes effect, so if you set Application.UseWaitCursor = true; then do some time-consuming process inside same function and set Application.UseWaitCursor = false; at the end, user won't see changed cursor at all, whereas setting Cursor property of a form takes effect immediately.

wxWidgets library makes it easy to change cursor to "busy" - as they call it - and restore it at the end of C++ scope by creating an object of class wxBusyCursor on the stack. It will change cursor in its constructor and automatically restore it in destructor of the object.

    wxBusyCursor busyCursor;
    // Lengthy process...

MFC library also has such class. It is called CWaitCursor.

If you know the way to show wait cursor in other GUI libraries, post it in a comment.

Comments | #wxwidgets #.net #mfc #gui Share

# Duplicated Values in C++ Enums

Jan 2012

There is a feature in C++ and other programming languages that allows assigning particular numeric values to elements in enums, even same values to many elements. I've recently heard somebody telling that it is completely useless. I can't agree with that. Let me give an example from the source of the scripting language I recently code at home. Enum representing language operators makes use of the order of numeric values to easily determine the number of arguments for each operator. I've defined special elements in this enum to mark the beginning of operators that take one, two or three arguments.

enum OP

    OP_NEG = OP_UNARY, // -x
    OP_BIT_NOT,        // ~x
    OP_LOG_NOT,        // !x
    OP_PRE_INC,        // ++x
    OP_PRE_DEC,        // --x
    OP_POST_INC,       // x++
    OP_POST_DEC,       // x--
    // ...

    OP_ADD = OP_BINARY, // x + y
    OP_SUB,             // x - y
    OP_MUL,             // x * y
    OP_DIV,             // x / y
    OP_MOD,             // x % y
    // ...



uint GetOpNumArguments(OP op)
    if (op == OP_UNKNOWN) return 0;
    else if (op < OP_BINARY)  return 1;
    else if (op < OP_TERNARY) return 2;
    else if (op < NUM_OPS)    return 3;
    else return 0;

Comments | #c++ Share

# Resizing Images to Generate Thumbnails in PHP

Jan 2012

Some time ago I came across a problem of calculating an image size for automatically generated thumbnail for gallery script coded in PHP. It required a moment's thought, so I'd like to share this algorithm. In fact there will be two algorithms.

First code scales the image down with following rules: Destination size will not exceed given thumbnail size, but the width or height can be smaller to always preserve aspect ratio. Images smaller than thumbnail size are not magnified.

$src_size_x, $src_size_y - Source image size.
THUMBNAIL_SIZE_X, THUMBNAIL_SIZE_Y - Constants defining thumbnail size.

$dst_size_x, $dst_size_y - Destination thumbnail size.

if( $src_size_x <= THUMBNAIL_SIZE_X && $src_size_y <= THUMBNAIL_SIZE_Y )
  $dst_size_x = $src_size_x;
  $dst_size_y = $src_size_y;
  $dst_size_x = THUMBNAIL_SIZE_X;
  $dst_size_y = (int)( $src_size_y * THUMBNAIL_SIZE_X / $src_size_x );
  if( $dst_size_y > THUMBNAIL_SIZE_Y )
    $dst_size_x = (int)( $src_size_x * THUMBNAIL_SIZE_Y / $src_size_y );
    $dst_size_y = THUMBNAIL_SIZE_Y;

Second algorithm also helps with generating image thumbnails, but works differently. It assumes that destination image will always be of size (THUMBNAIL_SIZE_X, THUMBNAIL_SIZE_Y), while source iamge can be cropped to select only the center of the image if it has different aspect ratio than the thumbnail.

Inputs to this algorithm are the same, while outputs are:

$src_x, $src_y - Offset in the source image to begin copying from.
$src_w, $src_h - Size of the rectangle to select from cropped source image.

The code that uses this algorithm should then select from the source image a rectangle with left-top position ($src_x, $src_y), size ($src_w, $src_h) and copy it, with scaling and resampling, to the destination image with the size exactly (THUMBNAIL_SIZE_X, THUMBNAIL_SIZE_Y). That's what imagecopyresampled function from GD library can do. This algorithm does not handle cases where source image is smaller than thumbnail.

$src_h = $src_size_y;
$src_w = (int)( $src_h * THUMBNAIL_SIZE_X / THUMBNAIL_SIZE_Y );

if( $src_w <= $src_size_x )
  $src_x = ( $src_size_x - $src_w ) / 2;
  $src_y = 0;
  $src_w = $src_size_x;
  $src_h = (int)( $src_w * THUMBNAIL_SIZE_Y / THUMBNAIL_SIZE_X );
  $src_x = 0;
  $src_y = ( $src_size_y - $src_h ) / 2;

Comments | #webdev #algorithms #php Share

# Fast, Heuristic Disk Search

Jan 2012

In March 2007 I've written an algorithm which I called "Fast, heuristic disk search" and published it in my article Szybkie, heurystyczne przeszukiwanie dysku (in Polish) on codeguru.pl. Today I went back to it, improved it a bit and I think it is a good opportunity to present it once again, this time in English :)

The problem is about searching hard disk, looking for a file or directory with particular name. Naive approach, which is used by file searching functions in programs like Total Commander, uses depth-first search, so it enters C:\, then C:\Program Files, then C:\Program Files\Adobe etc., spending lots of time in places where it probably won't find the file we are looking for.

Game developers know that searching algorithm can be significantly improved by using some heuristics that will drive algorithm towards (probably) right direction. We do it in A* pathfinding. Does a similar principle could be used also when searching for a file?

My particular problem was configuring a program with path to a console tool, let's say fxc.exe shader compiler from DirectX SDK. We could present a textbox where user has to enter path to this tool. We could also make "Browse" button with an open file dialog to simplify locating it. But wouldn't be great if program tried to locate it automatically on first run? Some installed programs store path in a registry key, but if it doesn't, we have no idea where could it be if we don't look for it among files and directories on hard disk.

My algorithm tries to locate given file or directory in given time limit by searching all given directories and their subdirectories. The improvement I propose here is inteligent management of the order in which we process these directories.

The algorithm uses two collections: a queue of directories to process and a set of already visisted directories. Here is the code in C#:

Read full entry > | Comments | #algorithms #.net Share

[Download] [Dropbox] [pub] [Mirror] [Privacy policy]
Copyright © 2004-2020