Variable Types in C vs Java

C contains five basic variable types, that will be familiar to you”

  • These are the int for integers,
  • the double and float for real numbers,
  • the char for single symbols (such as letters or numbers,
  • and the void which represents a non-type.

These all work more-or-less the same way they do in Java.

(Though void has extra uses in C, as we’ve already seen.)

Note: Like in Java, a char is really a very small int. Every character has an equivalent number. (For example, 'A' is 65.) If you wish to know them, review the “ASCII table”.

Unlike in Java, the sizes of these variables may vary from system to system. This is because C relies on the underlying hardware to define these types, and that can depend on many factors that are out of your control. The most common definitions are shown in Table 2, but you should understand that this might be different in your environment. If you believe that your system is different, you can determine the size (in bytes) of each using the C sizeof operator:

int intSize = sizeof(int); // 4 on most systems 

There are also four keywords that can be used to modify variables, which are also shown in Table 2. The long modifier increases the size of an int or double, whereas the short modifier makes a smaller int. The unsigned modifier restricts an int or char to be non-negative, doubling its range in positive territory. (By contrast signed is mostly redundant today, though on some systems it might be used to force an int or char to allow negative values.) C does not have a boolean type. Traditionally, one uses an int when one needs a true/false value: 0 means false, and nonzero (usually 1) means true. This calls for some care, as the following code will compile without an error message:

if (myValue = 4) { // bug: should be == 
}

In all probability, the programmer who wrote this intended to use a == to test if the variable holds a 4, and to execute the associated if block if it does. Instead, this code forces myValue to hold a 4, and then this block will always trigger because 4 is nonzero. This would not compile in Java, because the value in the parentheses is an int rather than a boolean.

C does not have a string type. Instead, we use char arrays. We’ll discuss this more in its own subsection below.

For the most part, the operations you are used to in Java work the same way in C. So when you see C code with +, -, *, /, %, +=, -=, ++, --, =, ==, <, <=, >, >=, +, &, |, ^, and so on, you should assume that they are working the way you would expect. However + cannot be used to concatenate strings (because they are char arrays). Also, because there are no booleans, &&, ||, and ! operate on ints in C - returning an int 0 for false, and nonzero for true. Finally, C has some extra operators that help direct memory management (&, *, and ->), that we will discuss when we talk about memory and data structures.

Casting variables works the same way in C as it does in Java, using types in parentheses such as (int).

Escape Sequence Used to Print  
\n newline  
\t tab  
"  
\\ \  

Table 3: Common Escape Sequences to print special characters in printf(). This is not a complete list.

Format Specifier Used to Print
%d int
%u unsigned int
%ld long int
%lu unsigned long int
%f float or double
%c char
%s string (i.e. char array)
%p pointer
%% percent sign

Table 4: Common Format specifiers for printf() and scanf(). There are many others in addition to these.

is always the string to print out. So the most basic example of printf() is the “hello world” example:

printf("Hello world!\n"); // basic output

Like in Java, you can print a newline by using the escape sequence \n. Other common escape sequences used to print special characters are shown in Table 3. printf() does not automatically append a newline to the end of its output like Java’s System.out.println() does, so be sure to do it yourself.

Unlike in Java, we cannot easily concatenate strings with other variables to output complicated sentences. If you want to print out non-string variables, you must use format specifiers, which are short codes that begin with a %. Each one necessitates a further argument in the printf(). The specifiers are locations in the string in which to insert the variables. For example, one of the most common specifiers is the %d, used to print an int:

int myValue = 6;
printf("The value is %d.\n", myValue); // "The value is 6."

This example has one extra argument corresponding to the %d: the variable to print. Here’s another example, that uses three format specifiers to print two numbers and their sum. Its printf() needs four arguments:

int num1 = 3, num2 = 9;
printf("%d + %d = %d\n", num1, num2, num1 + num2);
// prints "3 + 9 = 12"                                             

There are many format specifiers—a subset is shown in Table 4. If you are curious, you may look online to find others.

If you use the wrong specifier, it can result in undefined behavior (that can differ from system to system). For example, this code doesn’t work:

printf("%d\n", 4.0); // bug: prints weird number

The number to print is a double, but it is formatted as an int. Depending on your computer, it may print out the same wrong integer each time, or it may appear to print a random number. It’s trying to print out an int, but it cannot find it. Some systems might try to interpret the raw bits of 4.0 as if it were an int. Other systems might print out data from a nearby area of memory that hasn’t been initialized at all. If you get some weird outputs, it may pay to double-check that your format specifiers are correct.

It often tries to make printf() does not always print immediately.

execution more efficient by delaying printing until there’s a newline, and then printing everything at once. This can be frustrating when you’re debugging: if your program terminates unexpectedly, some things that you thought you printed before the crash will never appear. However, you can make sure that everything is printed out by “flushing the print buffer”. You can do this with fflush(), as shown here:

fflush(stdout); // makes sure everything's printed 

The argument stdout is the standard-out stream, which usually links to the terminal. It is a global variable defined inside of stdio.h.

The most common way to input a value from the keyboard is with scanf(). To get an int, one might do the following:

int userInput;                              
printf("Pick an integer: ");              
scanf("%d", &userInput); // input a number 

The & sign is very important for scanf() to work. We’ll discuss this in greater detail in the next section, when we talk about C and memory management. In brief, it tells the scanf() function where the argument is stored in memory, so that the variable can be modified—much like an argument in Java can be modified if it happens to be an object or an array.

Inputting a string from the user is more difficult. We will talk about how to do it when we discuss strings, below.


Licenses and Attributions


Speak Your Mind

-->