Anonymous
Anonymous

Reputation: 92

Incrementation using functions

I want to increment the value of a integer using functions in C.

So first I wrote a function inc where I incremented the value of integer v. Then in main function I declared a new variable a and incremented using inc(a) function.

Here is my code:

#include<stdio.h>
void inc(int v)
{
    v++;
}
int main()
{
    int a;
    scanf("%d",&a);
    inc(a);
    printf("%d",a);
    return 0;
}

But the output is same as the input value. It is not incrementing.

i.e If I give the input as 45,I am expecting the value 46 as output. But the output is still 45. Where am I going wrong? Someone please explain.

So I've done some research and found that the expected answer is coming when pointers are used and here is the code for that

#include<stdio.h>
void inc(int *v) {
    (*v)++;
}

int main() {
    int a;
    scanf("%d", &a);
    inc(&a);
    printf("%d", a);
    return 0;
}  

Why is the method without pointers is not correct?

Also in the second method why are we passing the argument as address i.e &a. Why can't we pass it as a?

I'm a newbie to C .So please help me with my doubts

Upvotes: 1

Views: 3291

Answers (6)

Manumerous
Manumerous

Reputation: 527

The problem is that by default c uses pass by value for functions. That means that if your calling the function the following way in your main,

int a = 45;
inc(a);

the function only gets to know the value 45 but not the variable a. It will therefore make a new local variable (int v in your case) that stores the value 45 and gets incremented. Since the function does not know anything about a, in particular not where a is located in memory it can not modify it. There are generally two ways to solve this:

  1. Using returns:

In this case the function keeps manipulating a local copy with the values of the arguments passed. In the end it can return the desired output of the function. This would be implemented the following way:

#include<stdio.h>
void inc(int v)
{
    v++;
    return v
}

int main()
{
    int a;
    scanf("%d",&a);
    a = inc(a);
    printf("%d",a);
    return 0;
}
  1. Passing the argument as a pointer:

In the second case, that you already found, your passing your argument by reference. This way the function gets to know the memory address of a and can therefore manipulate the value stored at a directly. The little star icon next to v in the function definition void inc(int *v) defines that the function takes an address as an input. Therefore, you have to pass the address of a by using &a as done in the code you posted.

Summary:

Your function, or any future functions you implement can be one of the two types above according to your needs. It should however, as a guideline, never manipulate values at passed addresses and return something at the same time. This can lead to confusion and results in a less readable code in general.

Upvotes: 2

"Why is the method without pointers not correct?"

If you use a pointer parameter, your intention is to point to an object in the caller. You can then modify this object in the called function. This is what is called pass by reference. You pass a reference to an object in the caller.

If you don't use a pointer, you just pass the value of the variable by value to the function, which means the value of the argument is assigned to a function-local variable. Inside of the function you can modify only the value of this function-local variable, but not an object in the caller.

What's the difference between passing by reference vs. passing by value?

Also in the second method why are we passing the argument as address i.e &a. Why can't we pass it as a?"

The & operator gains in this case the address of a, which is needed to be assigned to the pointer parameter.

A pointer always stores an address of an object to point to, not a value of the pointed object.

Without address, the pointer doesn't denote an object.


Please learn more about pointers and read a good C starting book like Modern C (You can get a free copy of it there).

This and others you can also find here:

The Definitive C Book Guide and List

It is usually explained in the first few chapters about functions and argument passing.

Upvotes: 2

Louis Go
Louis Go

Reputation: 2588

Short answer:

C is default pass by value. If pointer is not specified, a v in inc is just a copy of a in main with the same value.

That is, v++ would increase v in scope of inc but effects no others.

For pointer, (*v)++ means "add one value to where v points to"

If you're using C++, passying by reference is another solution.

Upvotes: 1

bogdyname
bogdyname

Reputation: 374

Pointer is a variable containing the address of an object. The pointer does not carry information about the contents of the object, but contains information about where the object is located.

Pointers are widely used in C programming. Pointers are often used when working with arrays.

Computer memory can be thought of as a sequence of numbered single-byte cells that can be accessed individually or in blocks.

Each variable in memory has its own address - the number of the first cell where it is located, as well as its value. A pointer is also a variable that is allocated in memory. It also has an address, and its value is the address of some other variable. A variable declared as a pointer occupies 4 bytes in RAM (in the case of a 32-bit version of the compiler).

A pointer, like any variable, must be declared.

сhar c;   // variable
char *p; // pointer
p = &c;  // p = address of c

Look at this exammple:

#include <stdio.h>
#include <stdlib.h>
int main()
{
  int a, *b;
  system("chcp 1251");
  system("cls");
  a = 134;
  b = &a;
  // %x = display the number in hexadecimal form
  printf("\n The value of the variable a is %d = %x hex.", a,a);
  printf("\n The address of the variable a is %x hex.", &a);
  printf("\n Data at pointer address b are equal %d = %x hex.", *b,*b);
  printf("\n The value of b pointer is %x hex.", b);
  printf("\n Location address of pointer b is %x hex.", &b);
  getchar();
  return 0;
}

Upvotes: 0

Rohan Bari
Rohan Bari

Reputation: 7726

Also in the second method why are we passing the argument as address i.e &a. Why can't we pass it as a?

You're here manipulating with pointer, when you change the value of address to that pointer, then the original value is also get changed.

In the other hand, when you pass the variable a by-value, it'll just make a copy and increment it in the function call, no changes will occur in the original value. The first method doesn't works because the variable passed in the function was pass-by-value type.

Edit: This question is now only tagged in C. But for extra inforamtion, there's a method to do it without pointers in C++, it's called pass-by-reference (manipulates with original copy of variables) which could be represented by an ampersand sign on the function signature, something like:

void changeRealValue(int& value) {
// _____________________^________
    value++; // original value is incremented now
}

Upvotes: 1

Prihex
Prihex

Reputation: 362

You always pass a copy of your variable, value or reference, to the function. So, sending a copy of the value will not affect the main function. However sending a copy of its reference will affect the main function because you say where your variable is in the memory.

Upvotes: 1

Related Questions