Skip to the page

Programming basics · core

Operators, pointers and passing arguments

In C, small details such as ++ in one line and pointer arithmetic are asked often. Say "undefined" when the language says so.

The notes

What you must know

  • i++ uses the old value and then adds one. ++i adds one and then uses the new value.
  • Changing the same variable twice in one expression with nothing to order the changes is undefined behaviour in C. Compilers may print different results. gcc and clang warn with -Wall.
  • A good answer says "undefined" first. Java fixes the order left to right, so Java gives one answer.
  • Pointer arithmetic: p + 1 moves by the size of the element, not one byte. arr[i] means *(arr + i).
  • *p + 1 is (*p) + 1. *p++ is *(p++): it gives the current value and then moves the pointer.
  • sizeof(arr) / sizeof(arr[0]) gives the element count only where arr is a real array. Inside a function, int arr[] is really a pointer, so sizeof gives the pointer size. Pass the length as a separate argument.
  • C has only call by value. swap(int x, int y) swaps copies. Pass addresses (pointers) to change the caller variables. C++ references are other names for variables.
  • A pointer can be NULL and can be pointed elsewhere. A reference must be set when created and cannot be re-seated. Java passes object references by value.

The red pen

Common traps: mistake → fix

  • Mistake: i = i++ + ++i has one right answer in C

    Fix: it is undefined behaviour.

  • Mistake: p + 1 moves one byte

    Fix: it moves one element.

  • Mistake: C has call by reference

    Fix: C passes everything by value; pointers carry addresses.

  • Mistake: sizeof gives the array length in a function

    Fix: it gives the pointer size.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does i++ + ++i print in C? In Java?
  2. What does this pointer code print? (arrays and *p++)
  3. Why does this swap function not swap?
  4. What is the difference between a pointer and a reference?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview