Data Types
Primitive types in C vs Java
Introduction
In this lesson, you'll learn about data types in C. Coming from Java, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Java, you're familiar with primitive types in c vs java.
C has its own approach to primitive types in c vs java, which we'll explore step by step.
The C Way
Let's see how C handles this concept. Here's a typical example:
// C types - platform-dependent sizes!
char c = 127; // at least 8 bits
short s = 32767; // at least 16 bits
int i = 2147483647; // at least 16 bits
long l = 2147483647L; // at least 32 bits
float f = 3.14f; // typically 32 bits
double d = 3.14159; // typically 64 bits
char ch = 'A'; // 8 bits (ASCII only)
int flag = 1; // no boolean type!Comparing to Java
Here's how you might have written similar code in Java:
// Java types - consistent sizes
byte b = 127; // 8 bits
short s = 32767; // 16 bits
int i = 2147483647; // 32 bits
long l = 9223372036854775807L; // 64 bits
float f = 3.14f; // 32 bits
double d = 3.14159; // 64 bits
char c = 'A'; // 16 bits (Unicode)
boolean flag = true;You may be used to different syntax or behavior.
C has no boolean - use int (0 = false, non-zero = true)
You may be used to different syntax or behavior.
char in C is 8-bit ASCII, not 16-bit Unicode
You may be used to different syntax or behavior.
int size varies by platform (use stdint.h for fixed sizes)
You may be used to different syntax or behavior.
No byte type in standard C
Step-by-Step Breakdown
1. No Boolean Type
Standard C has no boolean. Use int with 0 for false and any non-zero for true.
boolean isValid = true;
if (isValid) { ... }int isValid = 1; // 1 = true, 0 = false
if (isValid) { ... }
// C99 added: #include <stdbool.h>
// Then you can use: bool isValid = true;2. Fixed-Width Types
For guaranteed sizes, use stdint.h types.
#include <stdint.h>
int8_t b = 127; // exactly 8 bits
int16_t s = 32767; // exactly 16 bits
int32_t i = 2147483647; // exactly 32 bits
int64_t l = 9223372036854775807LL; // 64 bits
uint32_t u = 4294967295U; // unsigned 32 bits3. Character Handling
C chars are 8-bit ASCII. For Unicode, you need special handling.
char c = '中'; // Unicode works in Javachar c = 'A'; // ASCII only
// For Unicode, use wide chars:
#include <wchar.h>
wchar_t wc = L'中';Common Mistakes
When coming from Java, developers often make these mistakes:
- C has no boolean - use int (0 = false, non-zero = true)
- char in C is 8-bit ASCII, not 16-bit Unicode
- int size varies by platform (use stdint.h for fixed sizes)
Key Takeaways
- No boolean - use int (0 = false, non-zero = true)
- Type sizes vary - use stdint.h for guarantees
- char is 8-bit ASCII - use wchar_t for Unicode