Archive

Archive for the ‘c programming language’ Category

IDE for C under Windows

April 13, 2014 Leave a comment


Problem
A friend of mine asked me to help him in C programming. He has Windows. What IDE to use?

Solution
Code::Blocks is an excellent choice. It has an installer that also contains a C compiler. Awesome. Just install it and you are ready to develop. It has all the nice features that you expect from an IDE.

Code::Blocks is actually cross platform, thus it exists under Linux too! It’s also good for C++. It’s open source.

Categories: c programming language, linux, windows Tags: ,

The “Clockwise/Spiral Rule” of C

February 3, 2014 Leave a comment

There is a technique known as the “Clockwise/Spiral Rule” which enables any C programmer to parse in their head any C declaration.

Here it is: http://c-faq.com/decl/spiral.anderson.html.

C gibberish ↔ English

September 3, 2013 Leave a comment

See http://www.cdecl.org/.

Examples:

int *p
    declare p as pointer to int
int *p[]
    declare p as array of pointer to int
int (*p)[]
    declare p as pointer to array of int

Discussion @reddit.

Categories: c programming language Tags:

Dark corners of C

February 27, 2013 Leave a comment

A Quiz About Integers in C

The C language’s rules for integer operations have some quirks that can make even small programs behave in confusing ways. This post is a review of these rules in the form of a quiz containing 20 questions. I recommend going through the questions in order. If you are a beginning C programmer, you should consult a C book as you go through these questions since there are a lot of little things (such as what “1U” means) that I have not bothered to explain. If you are a serious C programmer, I expect you’ll do well — this quiz is not intended to be extremely difficult. You should assume C99. Also assume that x86 or x86-64 is the target. In other words, please answer each question in the context of a C compiler whose implementation-defined characteristics include two’s complement signed integers, 8-bit chars, 16-bit shorts, and 32-bit ints. The long type is 32 bits on x86, but 64 bits on x86-64 (this is LP64, for those who care about such things). Summary: Assume implementation-defined behaviors that Clang / GCC / Intel CC would make when targeting LP64. Make no assumptions about undefined behaviors.

Categories: c programming language Tags: ,

Binary representation of an int in C

November 27, 2012 Leave a comment

Problem

You want to visualize the binary representation of an int in C.

Solution

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

char * int2bin(int i)
{
    size_t bits = sizeof(int) * CHAR_BIT;

    char * str = malloc(bits + 1);
    if(!str) return NULL;
    str[bits] = 0;

    // type punning because signed shift is implementation-defined
    unsigned u = *(unsigned *)&i;
    for(; bits--; u >>= 1)
        str[bits] = u & 1 ? '1' : '0';

    return str;
}

int main()
{
    printf("%s\n", int2bin(0x3d));
    printf("%s\n", int2bin(-0x3d));

    return 0;
}

Output:

00000000000000000000000000111101
11111111111111111111111111000011

In the case of the negative number you can nicely see the two’s complement of the positive number.

I found the C source here.

Generate random numbers deterministically and non-deterministically

Problem
I wanted to compare the efficiency of some sorting algorithms. For this, I wrote a simple program that accepts a command-line parameter (the name of a sorting algorithm) and calls the specified algorithm on a large array containing random integers. Using the Unix “time” command I could do my tests.

However, if the array is filled up with different random numbers each time, the tests wouldn’t be fair. Thus, the array should contain random numbers that are generated in a deterministic way, i.e. each time I execute my little program, the array should be filled with the same numbers in the same order.

Generate random numbers deterministically
C snippet:

int UPPER = 10;

for (i = 0; i < 10; ++i) {
    printf("%d ", (int)(random() % UPPER + 1));
}

Full source code is here.

Python snippet:

UPPER = 10
random.seed(0)  # use a constant seed

for _ in range(10):
    print random.randint(1, UPPER),

Full source code is here. Doc on random.seed is here.

Sample output:

$ ./det.py
4 7 8 6 4 6 7 3 10 2
$ ./det.py
4 7 8 6 4 6 7 3 10 2

Generate random numbers non-deterministically
Now let’s see how to generate random numbers non-deterministically.

Note that this method is still deterministic since it uses the current time as its seed. If someone knows the time when you launched your program, (s)he could reproduce your “random” numbers. As John von Neumann said: “Any one who considers arithmetical methods of producing random digits is, of course, in a state of sin.

C snippet:

int UPPER = 10;

srand((unsigned)time(NULL));   /* use current time as seed */

for (i = 0; i < 10; ++i) {
   printf("%d ", (int)(random() % UPPER + 1));
}

Full code is here.

Python snippet:

UPPER = 10

for _ in range(10):
    print random.randint(1, UPPER),

Full code is here.

Sample output:

$ ./non-det.py
2 4 4 10 6 9 4 3 2 7
$ ./non-det.py
5 8 10 2 10 10 1 10 4 5

Note
Notice the different behaviors of C and Python. By default, C uses the same seed, thus if you want “true randomness”, you must call srand. On the other hand, Python generates “true random” numbers by default and you must provide a constant seed if you want a determinsitic behavior.

Thanks to Temia E. for his (her?) help.

clang: a C language family frontend for LLVM

March 5, 2012 Leave a comment

Clang is considered to be a production quality C, Objective-C, C++ and Objective-C++ compiler when targeting X86-32, X86-64, and ARM… If you are looking for source analysis or source-to-source transformation tools, clang is probably a great solution for you.

User’s Manual

Clang vs Other Open Source Compilers

Example

$ sudo apt-get install clang
$ clang hello.c
$ ./a.out
hello world

I didn’t dive into it but for “hello world” it works just like GCC :) I added some errors intentionally and the compiler told me exactly what and where the problem is. The warning/error messages were very informative.

Object-oriented programming in C

March 2, 2012 Leave a comment

Yes, it’s possible. See Axel-Tobias Schreiner’s book on this topic. Source code of the book is here.

Links

Learn C The Hard Way

February 25, 2012 Leave a comment

Learn C The Hard Way will fill in the “beginning programmer” gap in the literature on the C Programming language. It will teach good modern C programming practices and avoid habits that lead to buffer overflows, security defects, and other problems that even experienced programmers cause. This book is designed for:

  • Students who have read LPTHW or LRTHW.
  • Programmers with skill in one other “scripting” language.
  • Programmers who need to relearn C.
  • Objective-C programmers who want better C skills.
  • People who like a challenge.”

http://c.learncodethehardway.org/

Follow

Get every new post delivered to your Inbox.

Join 62 other followers