Data types, variables and constants
Precise meaning, syntax, sizes/ranges, literals, const vs #define, and safe type conversions for C data types, variables, and constants.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Engineers use C to control sensors, files, networks, and embedded devices; choosing the right data type and constant makes code correct, fast, and memory‑efficient. Understanding variables, constants, and conversions prevents overflow bugs, precision loss, and security issues.
Key ideas
- Constant: A constant is a value that does not change during execution. In C you can create constants using the
constqualifier (e.g.,const int N = 10;), enumeration constants (e.g.,enum { N = 10 };), and macro constants (e.g.,#define N 10). A literal (e.g.,42,3.14,'A', "Hello") is a constant value written directly in source code. - Identifier: An identifier is the name you give a variable, constant, function, type, etc. It must start with a letter (A–Z, a–z) or underscore
_, followed by letters, digits, or underscores, and is case-sensitive. - Declaration vs definition: A declaration introduces a name and its type to the compiler. A definition allocates storage. In C, a variable declaration with no
externand with or without an initializer is a definition; withexternand no initializer it is a declaration only. - Initialization: Giving an initial value when defining a variable. Local (block-scope) variables of arithmetic types that are not initialized have indeterminate values; file-scope variables (globals) are zero-initialized by default.
- Integer types: C provides signed and unsigned integers of different widths. Signedness and width affect range and behavior on overflow.
- Standard integer type families and minimum widths (bits):
char(≥8),short(≥16),int(≥16),long(≥32),long long(≥64).unsignedversions exist for all exceptboolandvoid. - The macro
CHAR_BIT(in<limits.h>) is the number of bits in acharand is at least 8. - A plain
charmay be either signed or unsigned; this is implementation-defined. Usesigned charorunsigned charwhen you need a specific behavior.
- Standard integer type families and minimum widths (bits):
- Two’s complement ranges (typical and, from C23, required): For an N‑bit unsigned integer, the exact range is 0 to 2^N − 1. For an N‑bit signed two’s complement integer, the exact range is −2^(N−1) to 2^(N−1) − 1. Earlier C standards allowed other signed representations; modern systems uniformly use two’s complement.
- Overflow rules: Unsigned integer arithmetic wraps modulo 2^N (defined behavior). Signed integer overflow is undefined behavior in C; programs must avoid it (e.g., by using wider types or checked arithmetic).
- Floating-point types:
float,double, andlong double. Most systems use IEEE 754 binary32 forfloatand binary64 fordouble. Floating-point has finite precision, rounding, possibleNaN(Not a Number) and infinities, and cannot exactly represent most decimal fractions (e.g., 0.1). - Type qualifiers:
- const: The object shall not be modified through that name. It enforces read‑only access at compile time but does not make the storage truly immutable by itself.
- volatile: Inhibits certain optimizations; used for memory-mapped I/O or data modified by interrupts/other threads.
- restrict: For pointers, tells the compiler that for the lifetime of the pointer, only it (or a value directly derived from it) accesses the object it points to (used for optimization). Covered in detail under Pointers and Functions topics.
- Derived types (brief): Arrays, pointers, structures, unions, functions, and enumerations are built from fundamental types. They are covered deeply in later topics (Arrays; Pointers; Structures and unions; Functions). Here, we use enum to define integer constants.
- Literals and suffixes:
- Integer literals: decimal (e.g.,
123), octal with leading0(e.g.,077), hexadecimal with0x/0X(e.g.,0x7B). Binary with0bappears in C23; older standards do not have it. - Integer suffixes:
U/u(unsigned),L/l(long),LL/ll(long long). Examples:42U,42L,42ULL. - Floating literals: with decimal point and/or exponent part:
3.14,2e3,1.0f(float),1.0(double),1.0L(long double). - Character constants:
'A', escape sequences like'\n','\x41'(hex),'\101'(octal). String literals:"Hello\n".
- Integer literals: decimal (e.g.,
- Implicit conversions and promotions:
- Integer promotions: types narrower than
int(e.g.,char,short) are promoted toint(orunsigned intin rare cases) when evaluating expressions. - Usual arithmetic conversions: when mixing types in expressions, the operands are converted to a common type (generally to the “higher rank” type, e.g.,
inttodouble). - Casting: An explicit conversion written as
(type) expression. Use casts carefully; they can hide bugs.
- Integer promotions: types narrower than
- Constants in practice:
constobjects have types and obey scope and visibility rules; they are checked by the compiler and respect type safety.#definemacro constants are preprocessor replacements without types; always parenthesize macro bodies to avoid precedence surprises.enumconstants are of typeint(or wider if needed) and are good for named integral constants.
- Exact statements commonly examined:
- Definition: “A data type in C defines the set of values, the operations permitted on those values, and the storage requirements.”
- Law (two’s complement range): “For an N‑bit two’s complement signed integer, the minimum representable value is −2^(N−1) and the maximum is 2^(N−1) − 1; for an N‑bit unsigned integer, the range is 0 to 2^N − 1.” Assumption: two’s complement representation; N is the width in bits of the type.
- Rule: “In C, signed integer overflow results in undefined behavior; unsigned integer arithmetic is performed modulo 2^N, where N is the width in bits of the unsigned type.” Assumption: standard C semantics.
- Rule: “Local (block-scope) variables of arithmetic type that are not initialized have indeterminate values; file-scope variables are zero-initialized.” Assumption: standard-compliant implementation.
- Rule: “In
printf, afloatis promoted todoublevia default argument promotions; therefore, use%fto print bothfloat(promoted) anddouble. Inscanf,%fexpectsfloat*and%lfexpectsdouble*.”
- What to draw if asked for a diagram: Draw a horizontal memory layout showing:
- For an 8‑bit
unsigned char, label bit positions b7 (MSB) to b0 (LSB), range 0..255. - For an 8‑bit two’s complement
signed char, label range −128..127 with b7 as sign bit. Under it, show example: 0110 0101 = +101, 1000 0000 = −128. Label “MSB”, “LSB”, “sign bit”, and “two’s complement”. Note: adjust bit width if your diagram uses 16 or 32 bits forint.
- For an 8‑bit
Formulas
type identifier = initializer;- Integer type modifiers and examples:
signed char c;unsigned short s;long int li;unsigned long long ull;
- Floating types and suffixes:
float f = 1.0f;double d = 1.0;long double ld = 1.0L;
- Constants:
- Const-qualified:
const type name = value; - Macro:
#define NAME value(use parentheses for expressions:#define SQR(x) ((x) * (x))) - Enumeration:
enum { NAME = value, OTHER = value2 };
- Const-qualified:
- Literals:
- Decimal integer:
int a = 42; - Octal integer:
int b = 052; // 42 decimal - Hex integer:
int c = 0x2A; // 42 decimal - Floating:
double pi = 3.141592653589793; - Char:
char nl = '\n'; - String:
char s[] = "Hello";
- Decimal integer:
- Type cast:
(target_type) expression
- Size and limits (headers):
sizeof(type)yields size in bytes<limits.h>:INT_MAX,LLONG_MIN,CHAR_BIT, etc.<float.h>:FLT_DIG,DBL_MAX,FLT_EPSILON, etc.
- Standard I/O format specifiers (common):
printf:%d(int),%u(unsigned int),%ld(long),%lld(long long),%f(double),%Lf(long double),%c(char),%s(string),%p(pointer),%zu(size_t),%g/%e(double in compact/exponential). Width/precision:%8.2f.scanf:%d(int*),%u(unsigned int*),%ld(long*),%lld(long long*),%f(float*),%lf(double*),%c(char*),%s(char[]),%zu(size_t*; in some libraries use%luwheresize_tisunsigned long). Always pass the address (&var) for non-arrays.
- Two’s complement range (if width is N bits):
- Signed:
min = −2^(N−1),max = 2^(N−1) − 1 - Unsigned:
min = 0,max = 2^N − 1
- Signed:
Worked examples
- Program: Using consts and floating literals for circle measures
Complete C code:
#include <stdio.h>
int main(void) {
const double PI = 3.141592653589793; // constant with type
double r;
printf("Enter radius in metres: ");
if (scanf("%lf", &r) != 1) {
printf("Invalid input\n");
return 1;
}
if (r < 0) {
printf("Radius cannot be negative\n");
return 1;
}
double area = PI * r * r; // double arithmetic
double circumference = 2.0 * PI * r; // 2.0 is a double literal
printf("Area = %.6f m^2\n", area);
printf("Circumference = %.6f m\n", circumference);
return 0;
}
Sample input:
2.5
Exact output:
Enter radius in metres: Area = 19.634954 m^2
Circumference = 15.707963 m
- Program: Safe average using wider integer to avoid overflow and using casts
Complete C code:
#include <stdio.h>
#include <limits.h>
int main(void) {
int a, b, c;
printf("Enter three integers: ");
if (scanf("%d %d %d", &a, &b, &c) != 3) {
printf("Invalid input\n");
return 1;
}
// Promote to long long to avoid overflow in the sum
long long sum = (long long)a + (long long)b + (long long)c;
// Integer average (truncates toward zero)
long long avg_int = sum / 3;
// Floating average with full precision
double avg_float = (double)sum / 3.0;
printf("Sum = %lld\n", sum);
printf("Average (integer) = %lld\n", avg_int);
printf("Average (floating) = %.6f\n", avg_float);
// Demonstrate unsigned modulo wrap (defined behavior)
unsigned int ua = 4000000000u; // 4e9 fits in 32-bit unsigned
unsigned int ub = 500000000u; // 5e8
unsigned int usum = ua + ub; // wraps modulo 2^32 on typical platforms
printf("Unsigned sum (wrap modulo 2^N) = %u\n", usum);
return 0;
}
Sample input:
1000000000 1000000000 1000000000
Exact output:
Enter three integers: Sum = 3000000000
Average (integer) = 1000000000
Average (floating) = 1000000000.000000
Unsigned sum (wrap modulo 2^N) = 205032704
Note: The last line demonstrates modulo wrap for 32-bit unsigned int. The exact number 205032704 is the result of (4,000,000,000 + 500,000,000) modulo 2^32 = 4,500,000,000 − 4,294,967,296 = 205,032,704.
- Program:
#definevsconstvsenumconstants and format specifiers
Complete C code:
#include <stdio.h>
#define TAX_RATE (0.18f) // macro constant (float)
#define MAX_ITEMS (5) // macro integer constant
enum { BUF_SIZE = 64, OK = 0, ERR = -1 }; // enum constants (integers)
int main(void) {
const int MaxUsers = 10; // const variable with type
const double Pi = 3.141592653589793; // const double
int items = MAX_ITEMS; // using macro constant
float price = 100.0f; // float literal with suffix f
float tax = price * TAX_RATE; // all float arithmetic
float total = price + tax;
char buffer[BUF_SIZE]; // using enum constant for size
(void)buffer; // silence unused warning
printf("MaxUsers (const int) = %d\n", MaxUsers);
printf("Pi (const double) = %.6f\n", Pi); // printf expects double for %f
printf("Items (macro) = %d\n", items);
printf("Price = %.2f, Tax = %.2f, Total = %.2f\n", price, tax, total);
printf("BUF_SIZE (enum) = %d, OK = %d, ERR = %d\n", BUF_SIZE, OK, ERR);
return 0;
}
Sample input:
(no input)
Exact output:
MaxUsers (const int) = 10
Pi (const double) = 3.141593
Items (macro) = 5
Price = 100.00, Tax = 18.00, Total = 118.00
BUF_SIZE (enum) = 64, OK = 0, ERR = -1
Common mistakes
- Octal trap: Writing
int x = 010;expecting ten but getting eight because of the leading zero (octal literal). Use decimal without leading zeros. - Signed overflow: Doing
int x = 2000000000 + 2000000000;causes undefined behavior on 32‑bitint. Promote to wider types before adding, or use checks. - Comparing floats for exact equality:
if (a == b)on floats can fail due to rounding. Compare with a tolerance:fabs(a-b) < 1e-6. - Modifying a
constobject or taking its non‑const pointer and writing through it. This violates theconstcontract; behavior can be undefined. - Macro pitfalls: Missing parentheses in macros like
#define SQR(x) x*xleading toSQR(1+2) == 5not 9. Always parenthesize parameters and the whole macro body. - Mixing signed and unsigned carelessly: Expressions like
if (i < v.size())in C++ or comparinginttosize_tin C can promote to unsigned and break logic. Be explicit about types. - Uninitialized locals: Using a local variable before assigning a value leads to indeterminate results.
For your exam
- Diagrams: Bit-level diagram of signed/unsigned representation and two’s complement; clearly label MSB/LSB and ranges. Mention assumptions (N‑bit width, two’s complement).
- Programs: Simple computation using constants, input/output with correct format specifiers, demonstrating safe integer arithmetic with wider types, and a program using
enum/const/#define. Include headers,mainsignature, input prompts, and exact sample I/O. - Numericals/theory: Derive the range formulas for N‑bit signed/unsigned integers from two’s complement representation. State assumptions (two’s complement, N bits). For floating-point, explain why 0.1 cannot be represented exactly and how rounding occurs (refer to
float.h). - Full-marks answers include: precise definitions, correct syntax, correct assumptions stated, accurate ranges with justification, correct format specifiers, and clean, compiling C code with sample I/O.
Quick check
- State the range of an N‑bit two’s complement signed integer and an N‑bit unsigned integer.
- Which specifiers do you use to read a
doublewithscanfand to print adoublewithprintf? - Name two advantages of using
constorenumover#definefor constants.
Answers: 1) Signed: −2^(N−1) to 2^(N−1) − 1; Unsigned: 0 to 2^N − 1. 2) scanf with %lf (argument type double*), printf with %f (argument type promoted double). 3) Type safety and scope/visibility checking by the compiler; better debugging and no precedence pitfalls (for enum, also participates in type system as an integer).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?