Computer Science and IT‹›⌂ 0:00 studied

Module 4 · 16 min read · Free chapter

Basics, data types and operators

In short

A C file passes through preprocessing, compilation, assembly and linking. Only sizeof(char) is fixed at 1; other sizes are implementation-defined. Unsigned arithmetic wraps around, signed overflow is undefined, and -1 < 1u is false. Precedence decides grouping, but i = i++ is undefined because i changes twice between sequence points.

What are you preparing for? We show the practice and previous year questions of your exam.

Start from zero: a program is a recipe

Think of the chai recipe card in a family kitchen. It lists what you need first, such as milk, tea leaves and sugar, and then gives steps in order: boil, add, wait, strain. A cook who follows the card exactly gets the same chai every time.

A C program works the same way. The top lines name the tools the program needs, and the function main holds the steps the computer follows, one after another. Here is the smallest useful program.

#include <stdio.h>      /* bring in printf */
int main(void) {
    printf("Namaste\n"); /* one step: print a line */
    return 0;           /* 0 means success */
}

The computer cannot read this text directly, because it understands only binary machine code. A program called the compiler translates the recipe into that code once, and after that the machine can run it as often as you like.

Why it matters. C is close to the machine, so every rule about sizes, conversions and operators decides the exact output. GATE asks you to predict that output by hand, which needs these rules to be sharp in your head.

Program structure, compilation stages and tokens

A C program is a collection of functions, and execution always begins at main. Lines that start with # are preprocessor directives. They are handled before real compilation, so #include <stdio.h> simply pastes in the declarations of printf and scanf.

Turning hello.c into a running program takes four stages.

  1. Preprocessing expands macros, pastes header files and removes comments, giving hello.i; gcc -E stops here.
  2. Compilation checks syntax and types and translates the code into assembly, giving hello.s; gcc -S stops here.
  3. Assembly converts assembly into machine code in an object file hello.o; gcc -c stops here.
  4. Linking joins the object file with library code, such as the body of printf, to make the executable.

A missing semicolon is caught in compilation, while calling a function that is declared but never defined fails only at linking. This difference is a favourite one-mark question.

Inside the compiler, the first job is to cut the text into tokens, the smallest meaningful units. C has six kinds: keywords (int, while, return), identifiers (total, _count), constants (42, 3.14, 'A'), string literals ("Namaste"), operators (+, ==) and punctuators (;, {).

An identifier must start with a letter or an underscore, may contain digits after that, and is case-sensitive, so Total and total are different. It cannot be a keyword, and C89 has 32 keywords. So 2nd and int are invalid names, while _2nd and Int are valid.

Why it matters. Knowing the stages tells you where an error comes from, which saves hours when a large project fails to build. Token rules also decide questions such as how many tokens x+++y has.

Data types and their sizes

Every variable in C has a type, which fixes how many bytes it occupies and how those bits are read. The basic types are char, int, float and double, and the modifiers short, long, signed and unsigned adjust them.

Here is the point exams love: only sizeof(char) is fixed, and it is 1 by definition. Every other size is implementation-defined. The standard promises only minimum ranges, so short and int have at least 16 bits, long at least 32 and long long at least 64, and it promises the order short ≤ int ≤ long ≤ long long.

Type Size on 64-bit Linux with gcc What the standard guarantees
char 1 byte exactly 1 byte
short 2 bytes at least 16 bits
int 4 bytes at least 16 bits
long 8 bytes at least 32 bits
long long 8 bytes at least 64 bits
float, double 4 and 8 bytes double is at least as precise as float
int * 8 bytes depends on the machine

We compiled a small program with gcc -std=c11 -Wall on a 64-bit Linux machine and printed these sizes, and the middle column is what it printed. On 64-bit Windows, long is usually 4 bytes, and on old 16-bit compilers int was 2 bytes. So when a GATE question says "assume int is 4 bytes", it is stating an assumption, not a law.

Two more facts surprise students. A character constant such as 'A' has type int in C, so sizeof('A') printed 4. A floating constant such as 3.0 is a double (8 bytes), while 3.0f is a float (4 bytes).

Why it matters. Code that assumes int is 4 bytes can break when moved to another machine. Fixed-width types such as int32_t from <stdint.h> exist for exactly this reason.

Signed, unsigned and overflow

An nn-bit unsigned type stores only non-negative values, from 0 to 2n−12^n - 1. With 8 bits that is 0 to 255, and with 32 bits it is 0 to 4,294,967,295. A signed type in two's complement stores −2n−1-2^{n-1} to 2n−1−12^{n-1} - 1, which is −128 to 127 for 8 bits.

Now picture a car odometer. When an unsigned value goes past its maximum, it wraps around to 0, and the standard says exactly this: unsigned arithmetic is done modulo 2n2^n. So the result is always defined, as these lines (compiled and run) show.

unsigned char c = 300;       /* 300 mod 256 = 44 */
unsigned int u = 0;
u = u - 1;                   /* wraps to 4294967295 */
unsigned short us = 65535;
us++;                        /* wraps to 0 */
printf("%d %u %u\n", c, u, us);   /* prints 44 4294967295 0 */

Signed types get no such promise. Signed overflow during arithmetic is undefined behaviour, so INT_MAX + 1 may give a negative number, a crash or anything else, and the optimiser may even assume it never happens. Converting an out-of-range value into a signed type is a softer case, called implementation-defined: (signed char)200 printed −56 with gcc, which is 200−256200 - 256.

The nastiest trap is mixing signed and unsigned. When a signed int meets an unsigned int, the signed value is converted to unsigned first. So -1 < 1u is false, because −1 becomes 4,294,967,295; our test printed "no" for this comparison. For the same reason sizeof(int) > -1 printed 0, since sizeof gives an unsigned size_t.

Why it matters. Many real security bugs began as a negative length compared with an unsigned size. GATE turns the same idea into output questions, so always ask which operand is unsigned before you compare.

Type conversion and promotion

C converts types automatically in three situations: in arithmetic, in assignment and when passing arguments. The first rule is integer promotion: a char or short operand is turned into int before any arithmetic. That is why 'A' + 2 is the int 67, and storing it in a char and printing with %c gives C.

The second rule is the usual arithmetic conversions. If the two operands have different types, the narrower one climbs to the wider one, roughly int, then unsigned int, then long, then float, then double. The type of the result is decided before the result is stored, and this causes the classic slip shown below.

int a = 10;
float c = a / 3;             /* int division first: 3, then 3.000000 */
printf("%f\n", c);           /* prints 3.000000 */
printf("%.2f %.2f\n", 5 / 2.0, (float)5 / 2);   /* prints 2.50 2.50 */
printf("%d\n", (int)3.99);   /* prints 3: the fraction is cut off */

A cast such as (float)5 converts one operand on purpose, so the division happens in floating point. Converting a floating value to an integer type simply drops the fraction, so (int)3.99 is 3, not 4.

Integer division with negative numbers truncates toward zero (guaranteed since C99). So -7 / 2 is −3 and -7 % 2 is −1, while 7 % -2 is 1. The rule that always holds is

(a/b)×b+a mod b=a(a / b) \times b + a \bmod b = a

where the slash stands for C's integer division, so the remainder takes the sign of the dividend.

Why it matters. Wrong averages, rupee totals that lose their paise and loops that stop early often come from an integer division hidden inside a float expression. Reading the type of every sub-expression is the habit that prevents them.

Operators, precedence and associativity

C has arithmetic (+ - * / %), relational (< <= > >= == !=), logical (&& || !), assignment (= += -= and so on), increment and decrement (++ --), the conditional operator ?:, the comma operator and sizeof. When several appear together, precedence decides which binds first, and associativity breaks ties between operators of equal precedence.

The order from highest to lowest that you must know is this.

  1. Postfix operators: function call (), subscript [], member . and ->, and postfix ++, --.
  2. Unary operators: ! ~ ++ --, unary minus, * (dereference), & (address), sizeof and casts, grouping right to left.
  3. Multiplicative * / %, then additive + -, then shifts << >>.
  4. Relational < <= > >=, then equality == !=.
  5. Bitwise AND &, then XOR ^, then OR |.
  6. Logical AND &&, then logical OR ||.
  7. Conditional ?:, then assignment = += -= and the rest, both grouping right to left, and last of all the comma.

Now apply it. In 2 + 3 * 4 - 6 / 2, multiplication and division go first, giving 2+12−3=112 + 12 - 3 = 11. In 10 - 4 - 3, left-to-right grouping gives (10−4)−3=3(10 - 4) - 3 = 3, not 9. In p = q = r = 5, right-to-left grouping sets r first, then q, then p.

Relational and logical operators return the int 1 or 0. So 1 < 2 < 3 is (1 < 2) < 3, that is 1 < 3, which is 1, while 3 > 2 > 1 is 1 > 1, which is 0. Both lines compile with only a warning, and both printed what this rule predicts.

Short-circuit evaluation is the other key rule. && stops as soon as the left side is 0, and || stops as soon as the left side is non-zero. The comma operator evaluates its left side, throws the value away and gives the right side.

int i = 0, j = 0, m = 3, n = 4;
int k = i++ || ++j;          /* i++ gives 0, so ++j runs */
int t = m > n ? m : n > 2 ? 100 : 200;
int c = (m++, n++, m + n);   /* value of the last part */
printf("%d %d %d %d %d\n", i, j, k, t, c);   /* prints 1 1 1 100 9 */

Why it matters. Guards such as (p != NULL && p->age > 18) are safe only because of short-circuit evaluation. Precedence slips like x & 1 == 0 are among the commonest bugs in real code.

Sequence points and undefined behaviour

Precedence tells you how an expression is grouped, but it does not tell you when each side effect happens. A side effect is a change to memory, such as the store done by i++. C only promises that all side effects are complete at certain checkpoints called sequence points.

The main sequence points are these: the end of a full expression (the semicolon), after the left operand of &&, || and the comma operator, after the condition of ?:, and just before a function is entered, once its arguments are evaluated. Between two such checkpoints, the rule is strict. If you modify a variable twice, or modify it and also read it for another purpose, the behaviour is undefined.

int i = 5;
i = i++;                     /* undefined behaviour */
int j = 5;
int k = j++ + ++j;           /* undefined behaviour */
printf("%d %d\n", x, x++);   /* undefined behaviour */

Undefined does not mean "some number we have to guess". It means the standard places no requirement at all, so different compilers, or the same compiler at another optimisation level, may print different things. With -Wall, gcc warned "operation on 'i' may be undefined" for these lines, and that warning is your signal.

A related but milder idea is unspecified order. In f() + g(), C does not say whether f or g runs first, and the arguments of a function call may be evaluated in any order. The program is legal, but if f and g both print, the output order may differ from compiler to compiler.

Code that is fully defined looks similar but has a checkpoint in between. i++; i = i + 1; is fine, and so is k = i++ && i++, because && is a sequence point. When a GATE option says "compiler dependent" or "undefined", choose it only when the code really breaks this rule.

Why it matters. Undefined code may pass every test on your laptop and fail on the server, which makes such bugs very hard to find. The exam rewards you for recognising them instead of guessing an output.

Bitwise operators and output prediction

Bitwise operators work on each bit separately. & gives 1 only where both bits are 1, | gives 1 where either bit is 1, ^ gives 1 where the bits differ, and ~ flips every bit. The shifts << and >> move bits left or right.

Take a=12a = 12, which is 1100 in binary, and b=10b = 10, which is 1010. Then a & b is 1000 = 8, a | b is 1110 = 14, a ^ b is 0110 = 6, a << 2 is 48 and a >> 2 is 3. For an unsigned value, a left shift by k multiplies by 2k2^k and a right shift by k divides by 2k2^k, dropping any remainder.

On a two's complement machine, ~0 is −1 and ~5 is −6, since ∼x=−x−1\sim x = -x - 1; gcc printed both. Two shifts are dangerous. Shifting by a negative count, or by at least the width of the type (such as 1 << 32 for a 32-bit int), is undefined, and right-shifting a negative number is implementation-defined; gcc gave −9 for -17 >> 1.

GATE often hides a classic trick inside a loop. The expression x & (x - 1) clears the lowest 1-bit of x, because subtracting 1 flips that bit and every 0 below it. For 44, which is 101100, the result is 101000 = 40.

unsigned int v = 29;         /* 11101 in binary */
int count = 0;
while (v) {
    v &= v - 1;              /* drop the lowest 1-bit */
    count++;
}
printf("%d\n", count);       /* prints 4 */

The loop runs once per 1-bit, so it counts set bits. A related check, x & (x - 1) == 0, is a bug because of precedence; the correct test for a power of two is x && !(x & (x - 1)). XOR also swaps two variables without a temporary: after p ^= q; q ^= p; p ^= q; the values 3 and 9 came out as 9 and 3.

Why it matters. Device drivers, network headers and permission flags such as read, write and execute are all handled bit by bit. GATE output questions in C often combine shifts with precedence, as in 1 << 3 + 1, which is 1 << 4 = 16.

Descriptive lens: how written papers ask this

Written papers for IT officer posts, state Assistant Programmer exams and university tests ask about C basics in four ways.

  1. They ask you to explain the stages from source code to executable and to name the error that each stage catches.
  2. They ask you to compare data types, signed and unsigned ranges, or implicit and explicit conversion, with small examples.
  3. They ask you to predict and justify the output of a short program, including why some lines are undefined.
  4. They ask you to write a small program, such as counting set bits or checking for a power of two with bitwise operators.

Practice questions (our own, not previous-year questions).

  1. Describe the four stages that turn a C source file into an executable, and state one error that each stage can report. (10 marks)
  2. Explain integer promotion and the usual arithmetic conversions, and show why -1 < 1u is false in C. (10 marks)
  3. What is undefined behaviour in C? Explain sequence points with two examples of undefined expressions and their safe rewrites. (15 marks)

Answer plan for question 3.

  • Define undefined behaviour as code for which the standard places no requirement, so any output or a crash is allowed.
  • Contrast it with implementation-defined behaviour, which each compiler must document, such as the size of int.
  • Explain that a sequence point is a checkpoint at which all earlier side effects are complete, and list the semicolon, &&, ||, the comma operator and function entry.
  • State the rule that an object must not be modified twice, or modified and read for another purpose, between two sequence points.
  • Give i = i++ and j++ + ++j as examples, and note that gcc with -Wall warns about both.
  • Give the safe rewrites i++; and j += 2; k = 2 * j - 1; or whatever result was intended, and conclude that clear code is also portable code.

Quick revision

  • Execution starts at main, and # lines are handled by the preprocessor before compilation.
  • The four stages are preprocessing, compilation, assembly and linking, and an undefined reference is a linker error.
  • Only sizeof(char) is fixed at 1; other sizes are implementation-defined, with minimum ranges.
  • Unsigned arithmetic wraps modulo 2n2^n, while signed overflow is undefined behaviour.
  • A signed value mixed with an unsigned one becomes unsigned, so -1 < 1u is false.
  • char and short are promoted to int, and 5 / 2 is 2 while 5 / 2.0 is 2.5.
  • Integer division truncates toward zero, so -7 / 2 is −3 and -7 % 2 is −1.
  • == binds tighter than &, shifts bind looser than +, and assignment groups right to left.
  • && and || short-circuit and give 1 or 0; the comma gives its right operand.
  • Modifying a variable twice between sequence points, as in i = i++, is undefined.
  • x & (x - 1) clears the lowest set bit, and ~x equals −x−1-x - 1 in two's complement.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 15 answered

  1. Execution of a C program begins at:

  2. A function is declared and called but never defined anywhere. The error is reported by the:

  3. Which gcc option stops after compilation and leaves an assembly (.s) file?

  4. Which is a valid C identifier?

  5. Which size is fixed by the C standard on every machine?

  6. With gcc on 64-bit Linux, `printf("%zu", sizeof('A'));` prints:

  7. `unsigned char c = 300; printf("%d", c);` prints:

  8. For a 32-bit `int` holding `INT_MAX`, the expression `INT_MAX + 1` is:

  9. `if (-1 < 1u) printf("yes"); else printf("no");` with 32-bit int prints:

  10. `int a = 10; float c = a / 3; printf("%f", c);` prints:

  11. In C (C99 and later), `-7 / 2` and `-7 % 2` are:

  12. What does `printf("%d", 5 & 3 == 1);` print?

  13. `int i = 0, j = 0; int k = i++ || ++j; printf("%d %d %d", i, j, k);` prints:

  14. The output of `int i = 5; i = i++; printf("%d", i);` according to the C standard is:

  15. `unsigned v = 29; int n = 0; while (v) { v &= v - 1; n++; } printf("%d", n);` prints:

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

Is the size of int always 4 bytes in C?

No. The standard only requires int to have at least 16 bits. It is 4 bytes with gcc on 64-bit Linux, but other systems may differ.

Why is -1 < 1u false?

When a signed int meets an unsigned int, it is converted to unsigned, so -1 becomes 4294967295, which is not less than 1.

What is the output of i = i++ in C?

There is no correct fixed output. The variable is modified twice without a sequence point, so the behaviour is undefined.

What does x & (x − 1) do?

It clears the lowest set bit of x. Repeating it until x becomes 0 counts the 1-bits, and it is 0 for a power of two.

More in this module: Programming in C

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Problem Solving through Programming in C (IIT Kharagpur, 106105171): program structure, data types, operators and expressions