C Variables & Types
Challenge Gallery
C Variables & Types
In Java, you write int x = 5; — and C is the same. The syntax for declaring variables is nearly identical. The difference is what happens underneath: C gives you no safety net.
Primitive Types
| Type | Size | Java Equivalent | Format |
|---|---|---|---|
char |
1 byte | char (but C’s is numeric) |
%c or %d |
short |
2 bytes | short |
%hd |
int |
4 bytes | int |
%d |
long |
8 bytes | long |
%ld |
float |
4 bytes | float |
%f |
double |
8 bytes | double |
%f or %lf |
Key Differences from Java
No booleans. C99 added _Bool (and <stdbool.h> gives you bool), but traditionally C uses int: 0 is false, anything else is true.
No strings. C has no String type. A “string” is a char * pointing to a null-terminated array: char *name = "hello"; stores {'h','e','l','l','o','\0'}.
No automatic initialization. In Java, int x; as a field defaults to 0. In C, a local int x; contains garbage — whatever was in that memory. Always initialize.
Implicit type conversion. C silently converts between types. int x = 3.9; silently truncates to 3. The compiler may warn, but it compiles. Java would require a cast.
printf Format Specifiers
int n = 42;
double pi = 3.14159;
char ch = 'A';
printf("%d\n", n); // 42
printf("%f\n", pi); // 3.141590
printf("%.2f\n", pi); // 3.14
printf("%c\n", ch); // A
printf("%d\n", ch); // 65 (ASCII value)
printf("%x\n", n); // 2a (hexadecimal)
scanf: Reading Input
int age;
printf("Enter age: ");
scanf("%d", &age); // & is required — gives scanf the ADDRESS of age
The & operator gives scanf a pointer to the variable so it can write to that memory location. Forgetting & is one of the most common C bugs.
sizeof
Use sizeof to check type sizes on your system:
printf("int: %zu bytes\n", sizeof(int)); // 4
printf("double: %zu bytes\n", sizeof(double)); // 8
printf("char: %zu bytes\n", sizeof(char)); // 1