CSS Computer Science (Optional) — Paper-I, Section-A, Topic II subtopic. Grouping data under one name, and manipulating data at the bit level.
Structures (struct)
- Groups different data types under one name; each member gets its own separate memory, so the struct's total size is (at least) the sum of its members' sizes
struct Student {
char name[20];
int age;
float gpa;
};
struct Student s1 = {"Ali", 20, 3.8};
printf("%s", s1.name); // dot operator to access members
- Members are accessed with the dot operator (
.) on a struct variable, or the arrow operator (->) via a pointer to a struct: ptr->name
- Nested structures: a struct can contain another struct as a member
- Structures can be passed to functions by value (a full copy) or by reference/pointer (to avoid copying and/or allow modification)
Unions
- Groups different data types under one name but all members share the same memory location — total size equals the size of the largest member, not the sum
union Data {
int i;
float f;
char c;
};
union Data d;
d.i = 10; // writing to i overwrites the same memory f and c would use
- Useful when only one of several possible types is needed at a time (memory-saving), e.g. representing a value that could be an int OR a float depending on context
- Writing to one member and then reading a different member gives meaningless/reinterpreted data — a frequently tested distinction from struct
Struct vs Union
|
struct |
union |
| Memory per member |
Separate for each |
Shared (overlapping) |
| Total size |
Sum of all members (plus padding) |
Size of the largest member |
| Simultaneous access |
All members valid at once |
Only the most recently written member is valid |
Enumerations (enum)
- A user-defined type consisting of a set of named integer constants, improving readability over "magic numbers"
enum Day {SUN, MON, TUE, WED, THU, FRI, SAT}; // SUN=0, MON=1, ... by default
enum Day today = WED; // today holds the integer value 3
Bit Manipulation Operators
| Operator |
Name |
Effect |
| & |
AND |
1 only if both bits are 1 |
|
|
OR |
| ^ |
XOR |
1 if bits differ |
| ~ |
NOT |
Flips every bit (1's complement) |
| << |
Left shift |
Shifts bits left; each shift multiplies by 2 |
| >> |
Right shift |
Shifts bits right; each shift divides by 2 (for unsigned/positive values) |
- Example:
6 & 3 → 0110 & 0011 = 0010 = 2; 6 | 3 → 0110 | 0011 = 0111 = 7; 6 ^ 3 → 0101 = 5