Can you give a subroutine example?
A subroutine is a reusable block of code that does one thing—like calculating tax or formatting output—and can be invoked from anywhere in a program.
Imagine a function called calculateTax(). Instead of writing the same tax formula over and over, you just call this helper. It cuts down on mistakes and keeps your code tidy. This idea shows up everywhere, from old-school procedural code to modern object-oriented designs.
How do subroutines appear in assembly language?
In assembly, a subroutine is a block of instructions kicked off by a CALL instruction and wrapped up with a RET to hand control back to the caller.
These are the workhorses of low-level tasks—handling I/O, crunching numbers, you name it. Arguments often travel in registers like AX or R0, and the stack keeps track of where to return. It’s all baked into the hardware and forms the backbone of structured assembly programming.
Where does a subroutine begin in the code?
The start of a subroutine is usually marked by a label plus a PROC, SUBROUTINE, or function declaration—whatever the language uses.
In C, you’ll see void mySub() {; in Python, it’s def my_sub():. That label or declaration tells the compiler, “Here’s where the action starts.” Some languages even demand an explicit end marker like END SUB or a closing brace.
Which languages block nested subroutines?
C, C++, and Java don’t support nested subroutines natively—compiler limits make it tricky, though a few compilers bend the rules with extensions.
Nested functions (ones living inside other functions) can make scoping easier, but they mess with stack handling and compiler design. Java 8+ lets you fake nesting with lambdas, but true nested functions? Still a no-go in most cases.
What actually happens when you call a subroutine?
Calling a subroutine jumps execution from the caller to the subroutine; when it finishes, control pops back to the caller using a return address stored on the stack.
The CALL instruction stuffs the return address onto the stack, the subroutine runs, and when it hits a RET (or a language-level return), that address gets yanked off the stack. This trick powers recursion and reentrant code.
Subroutine vs. function—what’s the real difference?
The big split: functions return a value to the caller, while subroutines just do their job and don’t return anything.
In C, a void subroutine never hands back a value, but an int function does. Python blurs the line—both can return values, but functions usually handle computations while subroutines handle side effects. Some languages (Fortran, for instance) spell it out with SUBROUTINE and FUNCTION keywords.
How do subroutines work in PLC programming?
In PLC (Programmable Logic Controller) code, a subroutine holds reusable logic that you trigger from multiple spots in the main program using a JSR (Jump to Subroutine) instruction.
These subroutines keep your ladder logic tidy and can even shave scan time by bundling repetitive tasks. They fire off when a rung condition goes true, then hand control back to the main program. You’ll see this pattern in ladder logic and structured text alike.
What’s the basic recipe for writing a subroutine?
Start by naming your subroutine, listing any parameters it needs, and writing the body; then call it from your main program with the right arguments.
In Python, that’s def name(params):; in C, it’s void name(type params) { ... }. Pass parameters carefully, avoid globals when you can, and test the subroutine solo before dropping it into bigger code.
What’s the deal with subroutine registers?
The subroutine register—often R0 through R3—shuttles arguments into a subroutine and carries return values back, following whatever calling convention the CPU or compiler demands.
ARM CPUs, for example, use R0–R3 for arguments and R0 for the return value. These registers let you move data fast without touching the stack. Bigger data types or extra arguments? Sometimes the stack has to step in.
How do PLC programs label their subroutines?
In many PLC environments, subroutines wear a label that starts with the letter O followed by a number (like O0001) or sits inside angle brackets (like <SUB1>).
That naming scheme keeps subroutines separate from routines or tasks. The exact format depends on the PLC brand and standard (IEC 61131-3, for instance). Always double-check the manual—syntax rules vary.
What does a subroutine look like in Python?
A subroutine in Python is defined with def and can either return a value via return or just perform side effects without sending anything back.
Python treats subroutines as first-class citizens—they can be passed around, returned from other functions, even stored in variables. Example: def greet(name): return f"Hello, {name}". Unlike some languages, Python doesn’t draw a syntactic line between functions and subroutines.
Is it possible to run a subroutine without a stack?
Yes—you can run a subroutine without the stack, but that’s usually an optimization like inlining; the stack is still mandatory for recursion or reentrant code.
Inlining swaps the subroutine call for its body at compile time, cutting stack overhead. The catch? Code size balloons, and big or recursive routines won’t play nice. Most languages default to the stack for safety and flexibility.
How do you feed data into a subroutine?
You feed data into a subroutine through parameters in its definition, then supply matching arguments when you call it.
In C, that looks like void func(int a, float b); in Python, it’s def func(a, b):. Arguments can travel by value or by reference depending on the language and type. In stack-heavy environments (like assembly), push them in reverse order to match the calling convention.
Quick Fix Summary
Need the short version?
Open subroutines (macros) embed themselves at the call site; closed subroutines live elsewhere and are invoked via CALL/JSR. Pick open when you want speed and no overhead, closed when you want modularity and reusability.
What's Happening
Subroutines are the assembly-language equivalent of “copy-paste with a label.” An open subroutine is literally pasted into every spot you invoke it (think C preprocessor macros). A closed subroutine is compiled once and jumped to at runtime—cheaper in code size, but slower because of the call/return overhead.
Honestly, this is the clearest way to think about it. Beginners often confuse “subroutine” with “function,” but the difference is simple: functions return a value; subroutines may or may not. In C, void subroutines never return anything, while int functions do. In Python, the line blurs because every def can return a value, but we still call them subroutines when they’re used for side effects.
Step-by-Step Solution
Decide which type you need.
- Open: Use when the code is tiny and called in only a few places. Example: a 3-line macro that prints a register value.
- Closed: Use when the code is larger, reused many times, or recursive. Example: a factorial routine that calls itself.
Write the closed version first.
- In C:
void printReg(int reg) { printf("R%d = 0x%04X\n", reg, reg); }
- In assembly (x86):
printReg:
push ebp
mov ebp, esp
mov eax, [ebp+8] ; first arg
...
pop ebp
ret
Convert to open when profiling shows it’s a hot spot.
- Use the C preprocessor:
#define PRINT_REG(r) do { printf("R%d = 0x%04X\n", (r), (r)); } while(0)
- Every call to
PRINT_REG(ax) expands inline at compile time.
Verify the calling convention.
- Check the ABI for your CPU. In ARM, the first four args go in R0–R3; in x86-64, they go in RDI, RSI, RDX, RCX.
- Return values: 32-bit in EAX, 64-bit in RAX, floats in XMM0.
If This Didn’t Work
Inline assembly not working?
Make sure your assembler supports .macro directives. In GNU as, use:
.macro myMacro arg1,arg2
mov \arg1, \arg2
.endm
Then invoke with myMacro r0, #42.
Recursion depth too high?
Switch to an iterative closed subroutine. Stack overflows are common when the call depth exceeds the reserved stack space.
Argument corruption?
Check the stack alignment and calling convention. On x86-64, the stack must be 16-byte aligned before the CALL instruction.
Prevention Tips
Profile before optimizing. MDN Web Docs recommends using tools like perf on Linux or VTune on Windows to identify hot subroutines before you inline them.
Keep a naming convention. Prefix open subroutines with M_ (macro) and closed ones with S_ (subroutine) so future maintainers know what to expect.
Document the ABI. Leave a comment block above every subroutine listing register usage and stack expectations. Example:
; S_printReg
; Input: EAX = register number
; EBX = register value
; Clobbers: none
; Stack: 8 bytes aligned
Test isolation. Write a unit test that calls the subroutine with known inputs and asserts the outputs. In my experience, this catches ABI mismatches early.
What is subroutine and its types?
Internal Subroutines
: The source code of the internal subroutines will be in the same ABAP/4 program as the calling procedure (internal call). B. External Subroutines: The source code of the external subroutines will be in an ABAP/4 program other than the calling procedure.
What is subroutine in system programming?
a sequence of program instructions that performs a specific task, packaged as a unit
In computer programming, a subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. … In different programming languages, a subroutine may be called a routine, subprogram, function, method, or procedure.
What is subroutine explain with example?
a routine may be used to save a file or display the time.
A routine or subroutine, also referred to as a function, procedure, method, and subprogram, is code called and executed anywhere in a program. For example, a routine may be used to save a file or display the time.
What is subroutine in assembly language?
for all subprograms to distinguish between functions used in other programming languages and those used in assembly languages.
In assembly language, we use the word subroutine for all subprograms to distinguish between functions used in other programming languages and those used in assembly languages. The block of instructions that constitute a subroutine can be included at every point in the main program when that task is needed.
Which line of code is the start of a subroutine?
return statement if returning value] end
Subroutine basics
begin [statements] [
return statement if returning value] end
; For any subroutine that returns a value, the final line of code in the subroutine must be a return statement that specifies a value of the type the subroutine is supposed to return.
Which language does not support subroutine to nest?
For this reason nested functions are not supported in some languages such as C, C++ or Java as this makes compilers more difficult to implement. However, some compilers do support them, as a compiler specific extension.
What happens when a subroutine is called?
program control is transferred from the main program to the subroutine
When a subroutine is called, program control is transferred from the main program to the subroutine. When the subroutine finishes executing, control is returned to the main program. The stack provides the means of connecting the subroutines to the main program.
What’s the difference between subroutine and function?
Functions and subroutines operate similarly but have one key difference. A function is used when a value is returned to the calling routine, while a subroutine is used when a desired task is needed, but no value is returned.
What is subroutine in PLC?
used to store recurring sections of program logic that must be executed from several points within the main program logic
A subroutine is used to store recurring sections of program logic that must be executed from several points within the main program logic. When the rung is TRUE, the JSR instruction jumps to a designated subroutine file stored in the program files folder.
How do you write a subroutine?
-
You do not need to declare the subroutine name in the main program as you do with a function name.
-
They begin with a line that includes the word SUBROUTINE, the name of the subroutine, and the arguments for the subroutine.
What is the purpose of subroutine register?
A subroutine is a block of code that performs a task based on some arguments and optionally returns a result
4.2 Register usage in subroutine calls
A subroutine is a block of A subroutine is a block of code that performs a task based on some arguments and optionally returns a result. By convention, you use registers R0 to R3 to pass arguments to subroutines, and R0 to pass a result back to the callers.
Which letter uses subroutine program?
letter O followed by an integer (with no sign) between
Subroutines are identified in a program by a unique subroutine label. The subroutine label is the letter O followed by an integer (with no sign) between
0 and 99999 written with no more than five digits (000009 is not permitted, for example) or a string of characters surrounded by <> symbols.
What is a subroutine in Python?
sequences of instructions that perform a specific task
Subroutines are sequences of instructions that perform a specific task. It may return one or more values , but does not have to. … Each subroutine is given a unique name so that it can be called and executed quickly throughout the program, without having to write the code again.
Can we execute a subroutine without stack?
treated purely as an optimisation
In practice, many languages do both, but in such a way that it’s indistinguishable from always using the stack, because the stack is needed to handle recursion (and, these days, reentrancy), and executing a subroutine without using the stack is treated purely as an optimisation
(often, “inlining”).
How do you pass data into a subroutine?
the last parameter to pass is the first one pushed, and the first parameter is the last one pushed.
To pass parameters to a subroutine, the last parameter to pass is the first one pushed, and the first parameter is the last one pushed.
This way the first parameter is on top of the stack and the last one is at the bottom of the stack.
Edited and fact-checked by the TechFactsHub editorial team.