1

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

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
Anonymous
  • 82
  • 2
  • 11
  • 3
    You need a book for C. 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". – Louis Go Jul 22 '20 at 07:49
  • 1
    C and C++ are very different (yet similar) languages. I recommend you do not try to learn both at the same time. Learn one first, and be ready to "unlearn" some of it when you start learning the other. – pmg Jul 22 '20 at 07:49
  • 1
    You would want to read up on the ways to pass an argument to a function: pass by value and pass by reference. – c_anirudh Jul 22 '20 at 07:50
  • Does this answer your question? [What's the difference between passing by reference vs. passing by value?](https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value) – RobertS supports Monica Cellio Jul 22 '20 at 08:12
  • @RobertSsupportsMonicaCellio I think not, because OP seems to be aware of exactly those language-agnostic concepts and just does not get how/why C does or does not support it. – Yunnosch Jul 22 '20 at 08:13
  • @Yunnosch I posted as an answer. Feel free to suggest edit if my description is unclear. – Louis Go Jul 22 '20 at 08:25
  • @Yunnosch OP asks "*Why is the method without pointers not correct?*" which is an indication for me that s/he doesn't even understand the concept. Hence the proposed duplicate. – RobertS supports Monica Cellio Jul 22 '20 at 08:28
  • @RobertSsupportsMonicaCellio That dupe is language-agnostic, though, and while it explains the differences between the two methods, here the OP are specifically asking about C, where the pass by "reference" is obtained by passing a pointer *by value*. Maybe there is a better dupe somewhere. – Bob__ Jul 22 '20 at 08:35
  • @Bob__ Well, Ok. There is for sure anywhere a dupe for C. We need to find it. – RobertS supports Monica Cellio Jul 22 '20 at 08:36
  • Does this answer your question? [Passing by reference in C](https://stackoverflow.com/questions/2229498/passing-by-reference-in-c) – Bob__ Jul 22 '20 at 08:39
  • Only my opinion: The total of good answers here AND linked in comments answers the question. I probably will use this as dupe for similar questions. In my opinion, none of the proposed duplicates does cover my understanding of this question. I only mention this in case you wonder why my close-vote is not there... – Yunnosch Jul 22 '20 at 09:03

6 Answers6

2

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.

Manumerous
  • 455
  • 6
  • 21
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.

1

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.

Prihex
  • 342
  • 2
  • 11
1

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
}
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
1

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.

Louis Go
  • 2,213
  • 2
  • 16
  • 29
0

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;
}
bogdyname
  • 358
  • 2
  • 10