Integer passing is functions

Home / C Programming / Integer passing is functions

Integer passing is functions


In C programming, when you pass an integer (or any other basic data type) to a function, the value of the integer is passed by value. This means that a copy of the integer's value is created, and the function works with this copy inside its scope. Any changes made to the copy do not affect the original value of the integer in the calling function.

Here's an example to demonstrate passing an integer to a function:


Output:

Before function call: number = 5

Inside the function: num = 10

After function call: number = 5

As you can see, the `modifyInteger` function receives a copy of the `number` variable from the `main` function. Inside the `modifyInteger` function, this copy is modified (doubled), but this modification does not affect the original `number` variable in the `main` function.

If you want to modify the original value of an integer inside a function, you need to pass a pointer to that integer as an argument. This way, the function can access the actual memory location of the integer and update its value directly. This concept is known as "passing by reference."

Here's an example of how to pass an integer by reference using a pointer:


Output:

Before function call: number = 5

Inside the function: num = 10

After function call: number = 10

Now, by passing the address of the `number` variable to the `modifyInteger` function, the function can directly modify the original `number` variable, and the changes are reflected in the `main` function.