C weird behaviour
Not really weird but interesting. The fact is, when we declare a function in C we can use "..." in the arguments to be able to get any number of any type of variable. In fact it is used in printf() and scanf(), and this gives bird to some interesting behaviour, for instance the code:
there from the previous function. We can even create a new function just to mess this up a bit more and do something like this:
int main()
{
int a,b;
printf("\nEnter two integers numbers:\n",&a,&b);
scanf("%d %d");
printf("%d %d\n",a,b);
return 0;
}
will print something like:
Enter two integers numbers:but how does scanf() knows I want to get those number at a and b? Those the printf() tells it to? I mean, I did sent the addresses of a and b to the printf() function so maybe it can tell the scanf() about it, right? Well, wrong, the truth is much simpler. The way a function in C works is by first transferring the values of the arguments into a special memory place and then jumps in to the function code itself. So first we sent a string and two addresses to integers to that memory space. So basically the printf() will read the string and because the string doesn't have any special character it doesn't even reads the other two variables. When the scanf() comes it will read the string that it got and see that it has to get two integers in some address that should be on that special place in the memory, so it will send them to the addresses on that memory space - which are still
1 2
1 2
there from the previous function. We can even create a new function just to mess this up a bit more and do something like this:
void hello(char *string,int *a,int *b)This is not a nice piece of code, but it works, it gets the right variables in the right memory addresses. Obviously none should write code like this. This is just a curiosity that you should be careful with when writing stuff in C.
{
}
int main()
{
int a,b;
printf("\nEnter to integers numbers:\n");
hello(0,&a,&b);
scanf("%d %d");
hello(0,a,b);
printf("%d %d\n");
return 0;
}
Comments
Post a Comment