Getting started
Function pointers
Operators
Data types
Arrays
Undefined behavior
Random numbers
Preprocessor and macros
Signal handling
Variable arguments
Files and I/O streams
Assertion
Linked lists
Generic selection
X-macros
Function parameters
Pointers
Structs
Sequence points
Command-line arguments
Aliasing and effective type
Compilation
Identifier scope
Bit-fields
Strings
Comman pitfalls
Error handling
Implicit and explicit conversions
Type qualifiers
Valgrind
Typedef
Selection statements
Declaration vs. definitio
Standard math
Boolean
Literals for numbers, characters and strings
Storage classes
Declarations
Formatted Input/Output
Compound literals
Inline assembly
Threads native
Initialization
Structure padding and packing
Memory management
Implementation-defined behaviour
Atomics
Iteration statements, loops, for, while, do-while
Enumerations
Jump Statements
Create and include header files
Testing frameworks
ctype.h characters classification
Pass 2D-arrays to functions
Side effects
Multi-character character sequences
Constrains
Inlining
Unions
Multi-threading
Common idioms and developer practices
Inter-process communication (IPC)
Comments
Contributors

Parameters are passed by value

suggest change

In C, all function parameters are passed by value, so modifying what is passed in callee functions won’t affect caller functions’ local variables.

#include <stdio.h>

void modify(int v) {
    printf("modify 1: %d\n", v); /* 0 is printed */
    v = 42;
    printf("modify 2: %d\n", v); /* 42 is printed */
}

int main(void) {
    int v = 0;
    printf("main 1: %d\n", v); /* 0 is printed */
    modify(v);
    printf("main 2: %d\n", v); /* 0 is printed, not 42 */
    return 0;
}

You can use pointers to let callee functions modify caller functions’ local variables. Note that this is not pass by reference but the pointer values pointing at the local variables are passed.

#include <stdio.h>

void modify(int* v) {
    printf("modify 1: %d\n", *v); /* 0 is printed */
    *v = 42;
    printf("modify 2: %d\n", *v); /* 42 is printed */
}

int main(void) {
    int v = 0;
    printf("main 1: %d\n", v); /* 0 is printed */
    modify(&v);
    printf("main 2: %d\n", v); /* 42 is printed */
    return 0;
}

However returning the address of a local variable to the callee results in undefined behaviour. See http://stackoverflow.com/documentation/c/364/undefined-behavior/2034/dereferencing-a-pointer-to-variable-beyond-its-lifetime#t=201608112325484278857.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents