Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
ASCII NUL, ASCII 0 ('0') and Numeric literal 0?
In C programming, it's crucial to understand the difference between ASCII NUL, ASCII '0', and the numeric literal 0. These are three distinct values with different purposes and representations.
Syntax
char asciiNul = '\0'; // ASCII NUL (null terminator) int zero = 0; // Numeric literal 0 char zeroChar = '0'; // ASCII character '0'
ASCII Values and Representations
- ASCII NUL ('\0') − Hexadecimal: 0x00, Decimal: 0
- ASCII '0' character − Hexadecimal: 0x30, Decimal: 48
- Numeric literal 0 − Integer value zero
Example: Demonstrating the Differences
The following program shows the ASCII values and usage of each type −
#include <stdio.h>
int main() {
char asciiNul = '\0'; // ASCII NUL (null terminator)
int zero = 0; // Numeric literal 0
char zeroChar = '0'; // ASCII character '0'
printf("ASCII NUL value: %d (hex: 0x%02X)<br>", asciiNul, asciiNul);
printf("Numeric zero value: %d<br>", zero);
printf("ASCII '0' character value: %d (hex: 0x%02X)<br>", zeroChar, zeroChar);
printf("ASCII '0' as character: '%c'<br>", zeroChar);
return 0;
}
ASCII NUL value: 0 (hex: 0x00) Numeric zero value: 0 ASCII '0' character value: 48 (hex: 0x30) ASCII '0' as character: '0'
Example: String Termination with ASCII NUL
ASCII NUL is used as the string terminator in C. Here's how it works −
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello"; // Automatically null-terminated
char str2[] = {'H', 'i', '\0'}; // Manually null-terminated
char str3[] = {'H', 'i'}; // NOT null-terminated (dangerous)
printf("String 1: %s (length: %lu)<br>", str1, strlen(str1));
printf("String 2: %s (length: %lu)<br>", str2, strlen(str2));
// str3 is not safe to print as string without null terminator
printf("String 3 chars: '%c' '%c'<br>", str3[0], str3[1]);
return 0;
}
String 1: Hello (length: 5) String 2: Hi (length: 2) String 3 chars: 'H' 'i'
Key Points
- ASCII NUL ('\0') has decimal value 0 and marks the end of strings in C
- Character '0' has decimal value 48 and represents the digit zero
- Numeric 0 is simply the integer value zero
- Never confuse '0' (character) with 0 (number) or '\0' (null terminator)
Conclusion
Understanding these three distinct representations is fundamental in C programming. ASCII NUL terminates strings, '0' is a printable character, and 0 is a numeric value − each serves different purposes in your programs.
Advertisements
