Tag Archives: c

On double and or

A small remark on programming conditionals. This is true for C and C++, but it might be true also for Java and other languages. I haven’t checked all of them.

It is about conditionals.

I’m seeing lots and lots of double OR and double AND in conditionals. In fact, I find it rare to see a single single operator these days. (Sorry, I couldn’t resist the pun). Almost without exception, every multiple conditional I see has the form:

if ((x>0) && (x<MAX_VAL))
{
   do something....
}

Which is kind of silly, really. The double operator && is the right thing to use when you have a complex conditional with function calls. But when all you do is compare arithmetical conditions? What one should do is use the simple single-operator

if ((x>0) & (x<MAX_VAL))
{
   do something....
}

Continue reading

Advertisements

Simple rules to avoid Memory Leaks in C

Below are several short tips which will help you survive C programming. I’ll be adding and amending this from time to time.

The most terrifying aspect of the C programming language is closely related to it’s core strength. Programming in C is all about using pointers – which are memory locations. Thus, in C, when you need a variable to work with to store numbers and manipulate them, you don’t have to deal with the variable directly – you use it’s address, instead. This is, of course, a really stupid thing to do when you just have to use a single variable to store a single number. But it is an enormously useful strategy when sending that variable off to a distant procedure, or when dealing with large arrays.

Continue reading