1

I have used this syntax for printing some variable n. I know that the syntax is wrong but was not able to understand what is happening behind the scenes. It is not even creating an error. Inside the main method:

int fac,p=1,n,i;
printf("Enter the value of n \n");
scanf("%d",&n);
printf("The factorial is \n %d"+n);

I have used +nin last line and that is not the right syntax. Input is 1 Output is:

he factorial is
1

Input is 5 Output is:

actorial is
1

Can someone help me to figure out what is happening behind the scenes? How is that the compiler understanding that +n in print function? From where the 1 is coming in the output?

Ashish sah
  • 755
  • 9
  • 17

1 Answers1

4

String literals are just pointers to char arrays. When you add an int to a pointer, you perform pointer-arithmetic, and move the pointer. Here, your factorial was 4, so you moved the pointer up 4 characters, so you lose the "The ".

The %d will just take the following value off the stack and interpret it as an int. In your case, this just happens to be 1.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Well expecting a bit elaborative explanation. – Ashish sah Jun 02 '18 at 08:35
  • your ans seems to be correct can you please explain pointer-arithmetic in simple words ? – Ashish sah Jun 02 '18 at 08:40
  • Ah. A challenge. Good luck @Mureinik , ;-) – Yunnosch Jun 02 '18 at 08:41
  • 1
    @Ashishsah - probably a good idea to (re)read that chapter in a book. – Ed Heal Jun 02 '18 at 08:42
  • @Ashishsah That means it increments the pointer by whatever you input, i.e It would more the starting point of your string forward, read more about it here https://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htm – supra28 Jun 02 '18 at 08:42
  • and what about the 1 which is coming at the last of the output. – Ashish sah Jun 02 '18 at 08:43
  • @Ashishsah If you have a pointer `p` pointing to an array element `a[i]` (as in `p == &a[i]`), then `p + n` is a pointer to `a[i + n]` (as in `p + n == &a[i + n]`). That's pointer arithmetic. – melpomene Jun 02 '18 at 08:44
  • Did you read the answer after the last few edits? It answers the question where the "1" is coming from. – Yunnosch Jun 02 '18 at 08:45
  • @Ashishsah in a nutshell, you move the pointer up and down the elements of the array according to the value of the int. See https://stackoverflow.com/q/394767/2422776 for a more detailed explanation. – Mureinik Jun 02 '18 at 08:45
  • @Ashishsah That is written in the answer. – supra28 Jun 02 '18 at 08:46
  • Well sorry did not looked at your edit thanks for your help @Yunnosch – Ashish sah Jun 02 '18 at 08:50