- 2067 Asar · 4 marks
Switch versus user defined function
Short answer
switch is a built‑in statement for multi‑way branching based on a value, cannot be called, and does not promote code reuse. A user‑defined function is a separately written, callable block of code that can accept arguments and return a value, supporting modularity.
State with example, how switch( ) function differs from user defined function in computer programming language C.
switch | User-defined function |
|---|---|
| A selection statement of the language (keyword) | A block of code written by the programmer, with a name |
| Chooses one of many blocks depending on a value | Performs a specific task and can return a value |
| Cannot be called, and takes no arguments | Is called from other places and can take arguments |
Written inside a function (such as main) | Written separately and defined once |
| Does not support code reuse | Supports code reuse and modularity |
#include <stdio.h>
int square(int n) /* user-defined function */
{
return n * n;
}
int main(void)
{
int choice = 2;
switch (choice) /* switch is a statement, not a function */
{
case 1: printf("One\n"); break;
case 2: printf("Square of 6 = %d\n", square(6)); break;
}
return 0;
}
Output:
Square of 6 = 36
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Significance of user defined functions · Computer Programming, chapter 6
- Define programming language · Computer Programming, chapter 1 · asked 3×
- How a function is defined in C · Computer Programming, chapter 6
- Computer program and programming · Computer Programming, chapter 2
- Function definition; sum of two numbers · Computer Programming, chapter 6
- Palindrome string using function · Computer Programming, chapter 7
- Convert user-defined type to basic type · Object Oriented Programming, chapter 5
- Higher-level language versus OO approach · Multimedia System, chapter 7
- Series programming of a third-order transfer function · Digital Control System, chapter 4 · asked 2×
- Ladder programming of a third-order transfer function · Digital Control System, chapter 4 · asked 2×