Showing posts with label smart code. Show all posts
Showing posts with label smart code. Show all posts

More readable way of casting primitive types in C++

How to cast a variable of one primitive type to another? Usually people use static_cast operator, but it can be done in other, more readable way.

Below example demonstrate the problem, and two solutions:

char var1 = 3;
char var2 = 5;

// first way
int result1 = static_cast<int>(var1 + var2);

// second way
int result2 = int(var1 + var2);

The same trick may be used e.g. when passing to a function an argument of different type that expected.

There is also C-style casting available in C++, but I didn't mention it above because it's discouraged.

Yes, I know, casting from one type to another is a common source of bugs, and can signify that overall design could be improved. That's true, but sometimes it's inevitable.

Is it possible to write a program in C without using semicolons?

Yes, it's possible! In this text I will show a set of tricks to do it. I will present this on a simple program that that reads two numbers from STDIN and prints theirs sum to the STDOUT.

Normally I would start this program from declaring two variables:

int a, b;

Unfortunately, there's a semicolon at the end of the line. It can be omitted by using variables already declared for the main function:

int main(int argc, char* argv[])

I will use argc as a and argv[0] as b. Normally, next thing would be reading two values from STDIN and placing them in a and b variables. It could be like this:

scanf("%d%d", &a, &b);

Once again, there's a semicolon! This one can be skipped by using 'if' statement:

if (scanf("%d%d", &a, &b)) {}

The same trick can be used for printing to STDOUT:

if( printf("%d", a + b ) ){}

Above code compiles and works correctly, but normally the main function should return zero if everything went OK:

return 0;

This semicolon can't be avoided by using the trick with 'if' statement, but we other construction can help here:

if(brk(0)){}

That's all, below is full source code:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
    if (scanf("%d%d", &argc, &argv[0])) {}
    if (printf("%d", argc+argv[0])) {}
    if (brk(0)) {}
}

Leave a comment, if you know other interesting riddles or tricks that can be used here!

Interesting way to check statuses returned by functions

If there is a set of bool functions, then sometimes below trick may be used to make the code that checks those values shorter:

bool status = true;
   
status &= foo_1();
status &= foo_2();
status &= foo_1();

printf(status ? "status: OK\n" : "status: NOK\n");

A simple trick to avoid "goto" statement

Error handling in C is sometimes done by using goto and labels. One of examples in the Linux kernel:

static struct avc_node *avc_alloc_node(void)
{
    struct avc_node *node;

    node = kmem_cache_zalloc(avc_node_cachep, GFP_ATOMIC);
    if (!node)  
        goto out;

    INIT_RCU_HEAD(&node->rhead);
    INIT_HLIST_NODE(&node->list);
    avc_cache_stats_incr(allocations);

    if (atomic_inc_return(&avc_cache.active_nodes) > avc_cache_threshold)
        avc_reclaim_node();
   
out:
    return node;
}

There's a trick with the usage of do/while construction that allows to write the same without using goto label. The idea is presented on below:

// with goto label
if (!bar()) {
    goto error;
}
someValue = baz();
error:
// with do/while construction
do {
    if (!bar()) {
        break;
    }
    someValue = baz();
} while (0);

Images hardcoded in a source code [PHP interpreter]

Abstract

Recently I presented a simple way to protect an image against saving, today I will show how PHP interpreter protect some of its images against changing.

Image may be hardcoded in a regular array, where each field contains corresponding value of a byte in the original image file. You may imagine that you open image in a hex editor, you see its content as a chain of values of the bytes, and then you retype them as a fields in your array (this can be automatized of course).

Smarter strings in C

In C, strings are usually stored in variables with char* type, it's just container for characters, there isn't stored other data/metadata. This can be tedious, e.g. if we want to iterate thought string we need to obtain its length (e.g by invoke strlen() function on it) or carry its length in some additional variables.

This can be simplified by wrapping raw char* string in a simple structure. Its string's length has unsigned type, therefore mistakes with assigning negative values will be easier to find. Its first argument is its content (with char* type), so it can be just passed to functions, that requires regular char* arguments (although it will create warning, it's safe IMHO).

Here is implementation:
#include <stdio.h>
#include <string.h>

typedef struct string {
    char* data;
    unsigned length;
} string;

int main() {
    string myHome;
    myHome.data = "it's big and white";
    myHome.length = strlen(myHome.data);

    // now we don't have to check for size of string,
    // e.g. we don't have to use strlen() to iterate thought charcters
    int i;
    for (i = 0; i < myHome.length; i++) {
        printf("%c", myHome.data[i]);
    }
    printf("\n");

    // backward compatibility with char*
    printf("%s\n", myHome.data);
    printf("%s\n", myHome); // this will raise warning but is legal
}

It's a bit unpopular trick, but may be seen in snippets on some forums, also here is tutorial about similar implementation of such strings.

How to replace modulo operator by using bitwise AND operator?

Modulo operation on a and b returns a reminder from dividing a by b. It can be implemented by using bitwise AND operator if b is a power of two.

Following samples in C and Python illustrate it.

#include <stdio.h>

int main() {
    // 8(dec) = 1000(bin)
    // 7(dec) =  111(bin)
    printf("19 mod 8 (with %%) %d\n", 19 % 8);
    printf("19 mod 8 (with &) %d\n",  19 & 7);

    // 16(dec) = 10000(bin)
    // 15(dec) =  1111(bin)
    printf("16 mod 16 (with %%) %d\n", 16 % 16);
    printf("16 mod 16 (with &) %d\n",  16 & 15);
}

bash-3.2$ llvm-gcc modulo.c && ./a.out
19 mod 8 (with %) 3
19 mod 8 (with &) 3
16 mod 16 (with %) 0
16 mod 16 (with &) 0
bash-3.2$ python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 19 % 8
3
>>> 19 & 7
3
>>> 

Why do we need to decrease b?

HOWTO avoid mistakes in conditional instructions

In C or C++ it's easy to made mistake in expression of conditional instruction and use assignment instead of comparison. It's presented in below snippet, where we want to check if x is equal to 6:

int main(){
    int x;

    /* first case */
    /* OK */
    if(x==6){
        /* sth */
    }
    /* WRONG */
    if(x=6){
        /* sth */
    }

    /* second case */
    /* OK */
    if(x!=6){
        /* sth */
    }
    /* WRONG */
    if(x=!6){
        /* sth */
    }

    return 0;
}

This code will be compiled successfully because its syntax is valid.

Those mistakes may be reduced by using following practice: while comparing something unmodifiable (string, number..) and variable, variable is written always on the right side. It's presented below:

int main(){
    int x;

    /* first case */
    /* OK */
    if(6==x){
        /* sth */
    }
    /* WRONG */
    if(6=x){
        /* sth */
    }

    /* second case */
    /* OK */
    if(6!=x){
        /* sth */
    }
    /* WRONG */
    if(6=!x){
        /* sth */
    }

    return 0;
}

Now conditional instructions with mistakes contain incorrect syntax and may be caught and fixed during compilation:

rgawron@foo:~$ gcc s2.c
s2.c: In function ‘main’:
s2.c:10: error: lvalue required as left operand of assignment
s2.c:20: error: lvalue required as left operand of assignment