← Back to C Course | Chapter 12: Advanced Topics | Lesson 20 of 20

C Interview Questions

Local vs. Global Variables

A local variable is declared inside a function and exists only for the duration of that function's execution, disappearing once the function returns, while a global variable is declared outside any function and persists for the entire lifetime of the program, visible from every function that doesn't shadow it.

Example: Local vs. Global Variables

c
#include <stdio.h>
int globalVar = 100;
void show() {
	int localVar = 5;
	printf("%d %d", localVar, globalVar);
}
int main() {
	show();
	return 0;
}

Value vs. Reference Parameters

Pass by value copies a variable's actual data into the function's parameter, so changes made inside the function never affect the caller's original variable, whereas pass by reference (achieved in C using a pointer) passes the variable's address, letting the function modify the original data directly through that pointer.

Example: Value vs. Reference Parameters

c
#include <stdio.h>
void byValue(int x) { x = 100; }
void byRef(int *x) { *x = 100; }
int main() {
	int a = 5;
	byValue(a);
	byRef(&a);
	printf("%d", a);
	return 0;
}

Structure vs. Union

A struct allocates separate, independent memory for every one of its members, so all fields can be read or written simultaneously without affecting each other, while a union allocates a single shared block of memory sized for its largest member, meaning only one member holds a valid value at any given time.

Example: Structure vs. Union

c
#include <stdio.h>
struct S { int a; int b; };
union U { int a; int b; };
int main() {
	printf("%zu %zu", sizeof(struct S), sizeof(union U));
	return 0;
}

Why is gets() Dangerous?

gets() reads a line of input into a buffer with absolutely no way to limit how many characters it writes, so any input longer than the buffer silently overwrites adjacent memory — a classic buffer overflow vulnerability. It was formally removed from the C standard for exactly this reason; fgets() is the safe replacement.

Example: Why is gets() Dangerous?

c
#include <stdio.h>
int main() {
	char buffer[10];
	printf("Use fgets() instead of gets()");
	return 0;
}

What is a Null Pointer?

A null pointer is a pointer explicitly set to the value NULL to indicate it doesn't currently point at any valid object, which is the conventional way to represent 'no target yet' and lets code check if (ptr != NULL) before dereferencing to avoid crashing on an uninitialized or already-freed pointer.

Example: What is a Null Pointer?

c
#include <stdio.h>
int main() {
	int *ptr = NULL;
	printf("%d", ptr == NULL);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.