C Tutorial (13) : Conditional operators, Increment-Decrement operators and sizeof()

C operators sometimes substitute for more wordy commands that you would use in other programming languages. Not only can an assortment of operators speed your program development time, but they also compile more efficiently and run faster than commands. The C operators do a lot to make C the efficient language that it is.

Conditional operators

The conditional operator is the only C operator that requires three arguments. Whereas division, multiplication, and most of the others require two values to work, the conditional operator requires three. Although the format of the conditional operator looks complex, you will see that it streamlines some logic and is actually straightforward to use.

The conditional operator looks like this: ?:. Here is its format:

relation ? trueStatement : falseStatement;

The relation is any relational test, such as age >= 21 or sales <= 25000.0. You also can combine the relational operators with the logical operators. The trueStatement is any valid C statement, and the falseStatement is also any valid C statement. Here is an example of a conditional operator:

(total <= 3850.0) ? (total *= 1.10): (total *= 1.05);

Note : The parentheses are not required, but they do help group the three parts of the conditional operator so that you can see them easier.

If the test in the first set of parentheses is true, the trueStatement executes. If the test in the first set of parentheses is false, the falseStatement executes. The conditional operator you just saw does exactly the same thing as this if…else statement:

if (total <= 3850.0 )
  { total *= 1.10; }
else
   { total *= 1.05; )

Just about any if…else statement can be rewritten as a conditional statement. The conditional requires less typing, you won’t accidentally leave off a brace somewhere, and the conditional runs more efficiently than an if…else because it compiles into more compact code.

Tip : The format of the conditional operator is obvious when you think of it like this: The question mark asks a question. Keeping this in mind, you could state the earlier example as follows: Is the total <= 3850.0? If so, do the first thing; otherwise, do the second.

C programmers don’t like the redundancy you saw in the earlier use of the conditional operator. As you can see, the total variable appears twice. Both times, it is being assigned a value. When you face such a situation, take the assignment out of the conditional operator’s statements:

total *= (total <= 3850.0) ? (1.10): (1.05);

Don’t replace every single if…else with a conditional operator. Many times, if…else is more readable, and some conditional statements are just too complex to squeeze easily into a conditional operator. However, when a simple if…else is all that’s needed, the conditional operator provides a nice alternative.

The conditional operator offers one additional advantage over if: The conditional often can appear in places where if can’t go. The following print(f) prints a trailing s if the number of pears is more than 1:

printf("I ate %d pear%s\n", numPear, (numPear>1) ? ("s.") : ("."));

If the value in numPear is greater than 1, you’ll see something like this printed:

I ate 4 pears.

But if there is only one pear, you’ll see this:

I ate 1 pear.

Operators: ++ and – –

Although the conditional operator works on three arguments, the increment and decrement operators work on only one. The increment operator adds 1 to a variable, and the decrement operator subtracts 1 from a variable.

Incrementing and decrementing variables are things you would need to do if you were counting items. The increment operator is ++, and the decrement operator is – -. If you want to add 1 to the variable count, here’s how you do it:

count++;
You also can do this:
++count;

The decrement operator does the same thing, except that the 1 is subtracted from the variable. You can do this:

count--;
You also can do this:
--count;

As you can see, the operators can go on either side of the variable. If the operator is on the left, it’s called a prefix increment or prefix decrement operator. If the operator is on the right, it’s known as a postfix increment or postfix decrement operator.

Note : Never apply an increment or decrement operator to a literal constant or an expression. Only variables can be incremented or decremented. You will never see this:

--14;          /* Don't do this! */

Prefix and postfix operators produce identical results when used by themselves. Only when you combine them with other expressions does a small “gotcha” appears. Consider the following code:

int i = 2, j = 5, n; 
n = ++i * j;

The question is, what is n when the statements finish executing? It’s easy to see what’s in j because j doesn’t change and still holds 5. The ++ ensures that i is always incremented, so you know that i becomes 3. The trick is determining exactly when i increments. If i increments before the multiplication, n becomes 15, but if i increments after the multiplication, n becomes 10.

The answer lies in the prefix and postfix placements. If the ++ or — is a prefix, C computes it before anything else on the line. If the ++ or — is a postfix, C computes it after everything else on the line finishes. Because the ++ in the preceding code is a prefix, i increments to 3 before being multiplied by j. The following statement increments i after multiplying i by j and storing the answer in n:

n = i++ * j;                   /* Puts 10 in n and 3 in i */

The preceding statement replaces the following two statements that you would have to write in other programming languages:

n = i * j; 
i = i + 1

Note : The ++ and — operators are extremely efficient. If you care about such things (most of us don’t), ++ and — compile into only one machine language statement, whereas adding or subtracting 1 using +1 or -1 doesn’t always compile so efficiently.

sizeof

You use sizeof() to find the number of memory locations it takes to store values of any data type. Although most C compilers now use 4 bytes to store integers, not all do. To find out for sure exactly how much memory integers and floating points are using, you can use sizeof(). The following statements do just that:

i = sizeof(int); // Puts the size of integers into i. 
f = sizeof(float); // Puts the size of floats into f

sizeof() works on variables as well as data types. If you need to know how much memory variables and arrays take, you can apply the sizeof() operator to them.

char name[] = "Ruth Claire";
int i = 7;

printf("The size of i is %d.\n", sizeof(i)); 
printf("The size of name is %d.\n", sizeof(name));

Here is one possible output from this code:
The size of i is 
The size of name is 12

Depending on your computer and C compiler, your output might differ because of the differences in integer sizes. Notice that the character array size is 12, which includes the null zero.

Note : The length of a string and the size of a string are two different values. The length is the number of bytes up to but not including the null zero, and it is found via strlen(). The size of a string is the number of characters it takes to hold the string, including the null zero.

Logical operators < Prev                                                    Next > While & Do….while

2 comments

Leave a reply to C Tutorial (12) : Logical operators – Anukul Verma Cancel reply