Wrong output while running C code [duplicate] - c

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 4 years ago.
Possible Duplicate:
Parameter evaluation order before a function calling in C
For the below code I expected the output to be 20 and 76 but instead 75 and 21 is comming as output .Please explain why is so.
#include<stdio.h>
unsigned func(unsigned n)
{
unsigned int a =1 ;
static unsigned int b=2;
a+=b; b+=a;
{
unsigned int a=3;
a+=b; b+=a;
}
//printf("%d %d ",a,b);
return (n+a+b);
}
int main()
{
printf("%d %d\n",func(4),func(5));
return 0;
}

you are expecting func(4) to be called before func(5) but the opposite happens with your compiler. The order of evaluation of function parameters is unspecified by C standard. So, compiler is free choose which function to call first. So across different runs you may observe different order of function calls, though it's very unlikely to happen that way with the same compiler.

The order of evaluation of func(4) and func(5) isn't defined by the C standard(s).

The order of evaluation of expression is unspecified behaviour hence func(4) and func(5) may be called in different order as you supposed to
You might like to visit it for more
Compilers and argument order of evaluation in C++
Parameter evaluation order before a function calling in C

The arguments are pushed onto stack in reverse order. It seems in your compiler implementation, func(5) is called before func(4).

Order of evaluation could be the reason. Because,
//printf("%d %d\n",func(4),func(5));
printf("%d \n",func(4));
printf("%d \n",func(5));
prints
20
76

func(5) is getting executed first :
Values of variables after executing func(5) :
a = 3
b = 13
func(5) = 21
Since, b is static, the values after executing func(4):
a = 14
b = 57
func(4) = 75

The code is simple, and remember static variables will preserve their values between function calls.
In your program, due to your compiler(thus compiler specific, not defined by standards):
func(5) is executed first, : which returns 21..
explanation:
unsigned func(unsigned n) /*first with 5*/
{
unsigned int a =1 ;
static unsigned int b=2;
a+=b; b+=a; // a = 3, b = 5
{
unsigned int a=3;
a+=b; b+=a; // a = 8, b = 13
}
//printf("%d %d ",a,b);
return (n+a+b); // 5 + 3 + 13 = 21.
}
func(4) is executed next,
explanation:
unsigned func(unsigned n) /*first with 5*/
{
unsigned int a =1 ;
static unsigned int b=2;
a+=b; b+=a; // a = 14, b = 27
{
unsigned int a=3;
a+=b; b+=a; // a = 30, b = 57
}
//printf("%d %d ",a,b);
return (n+a+b); // 4 + 57 + 14 = 75(which is printed first).
}
Hence the output.

There is a well known term for this called "function side effects". You change a variable inside a function, call the function and rely upon a statement using the variable expecting it to have already changed. Generally this should be avoided and is not a good approach.
A better alternate in such a scenario is either call function and store the return values and then use them in printf or make two different printf calls.
side effects

Related

Why different values inside called function and inside calling function?

The values which are output from inside the called function and from inside the calling function are not identical.
Why are values of y and value of m not the same?
screenshot of code and output, showing "Value of m 6" and "value of y 13"
#include<stdio.h>
int pass(a);
int main()
{
int x,y;
printf("Hello world\n");
printf("Enter the x ");
scanf("%d",&x);
y = pass(x);
printf("value of y %d",y);
return 9;
}
pass(m)
{
m = m + 5;
printf("Value of m %d\n",m);
// return 5;
}
Output:
Hello World
Enter the x 1
Value of m 6
value of y 13
Strictly, this should not even attempted to be explained, because of undefined behaviour, compare Reaching end of function without return statement
but ...
Assuming that my guess on the pattern of returned values (a constant plus the number of digits in "input + 5") is correct:
By chance, the default assumptions of the compiler when seeing the incomplete prototype int pass(a); (should be int pass(int a);), allow it to associate the later provided implementation of pass(m) (should be int pass(int m);, or more consistently int pass(int a)).
So when you call y = pass(x);, y gets the value returned by that implementation.
The implementation then lacks a clean return statement (it has one, but inactive by being a comment).
So at the end of executing that function, the most recently determined result is returned, another default of compilers which you should better not rely on for clarity and readability of code.
The most recent result is the return value of the call to printf().
That return value is the number of successfully printed characters.
You might want to read up on printf() and its return value in its specification, and about the concept of return values, prototypes and data types of parameters and return values in general.
For the output you show in your picture of text,
Value of m 6\n (thanks for making me type that...) that is, let me count
^ ^ ^ ^
1 5 10 13,
13, including the newline at the end of the output from inside the function.
Obviously, this is completely unrelated to the value of the local variable m, which is seen in the picture of text.
For more details on how to achieve what you might try to do see the comment David C. Rankin.

C Left Shift Operator [duplicate]

This question already has answers here:
order of evaluation of function parameters
(5 answers)
C/C++ - evaluation of the arguments in a function call [duplicate]
(5 answers)
Closed 2 years ago.
I have the following program:
#include <stdio.h>
int main ()
{
int x = 8;
printf("%d %d %d ", x++, x << 2, x >> 1);
}
The way I feel like this is supposed to go is this way:
The first number should be 8. Then it gets incremented to 9. 9<<2 is 36 so the second %d is 36. The last one is 8 >> 1 which is 4.
However, when I put this into the compiler I get '8 32 4' and not '8 36 4'.
Can someone explain why please?
Thank you!
This operation invokes an Undefined Behavior.
The gcc executes the way you observe, clang does it another way as the result of this program is undefined.
clang also issues a warning
https://godbolt.org/z/GzhPKn
The make program result defined:
int main ()
{
int x = 8;
x++;
printf("%d %d %d ", x, x << 2, x >> 1);
}
Argument evaluation order in C and C++ is undefined. Whether the increment or one of the shifts happens first depends on implementation and compiler optimization. It is never advisable to write code like this.
int a() { printf("A"); return 0; }
int b() { printf("B"); return 0; }
int c() { printf("C"); return 0; }
If you do:
printf("%d%d%d", a(), b(), c());
It doesn't necessarily mean you'll get an ABC on your console. Ignore the 0s.

My function will give correct answers on only one call but not on multiple

I'm making a code for converting Decimal numbers to Binary(university assignment). If I only do DecToBinary(5) it gives me 101, and if I only do DecToBinary(6) it gives me 110, but when i do both of these statements in main() it gives me 101110101 when it should just give me 101110(joining the two answers above). I don't understand what is going on since it should just call DecToBinary(5) and print 101 then (without adding a newline character) call DecToBinary(6) and print 110.
void DecToBinary(int dec){
int temp[64]; //64 is just a max value
int i,j;
while(dec>0){
temp[i]=dec%2;
dec=dec/2;
i++;
}
for(j=0;j<i;j++){
printf("%d",temp[i-1-j]);
}
}
You haven't initialized the variable i. This means that the behaviour of your program is undefined, as the value of i may be different of 0 which is what you want.
To correct it, you just have to initialize i when declaring it, meaning int i = 0
The variable i is not initialized
int i,j;
so the function has undefined behavior.
You need to initialize it before the while loop.
Also the while loop should be substituted for a do-while loop. Otherwise the value 0 will not be processed correctly. For example
i = 0;
do
{
temp[i++] = dec % 2;
} while( dec /= 2 );
Also as the function does not process negative numbers then its parameter should have the type unsigned int
void DecToBinary( unsigned int dec )
Always initliaze variable. Check i and j in your case.

Function returns int but getting strange behavior

I wrote some code to count the bits in a word. When I printf() the count it prints 32 as expected but when I stuck the same code in a function and printed the return value it gives me some crazy large number.
I then copy/pasted the code back into main() printed the count and printed the return value of my function at the same time and hey both gave me 32 but if I then comment out the code in main() my function again prints the large number.
Anyone have an idea about why this is happening?
#include <stdio.h>
int wordlength();
int main() {
printf("%d", wordlength()); // prints 4195424 but
// if I uncomment the code below
// it then prints 32 like I want
// int count;
// unsigned int n = ~0;
//
// while( n != 0) {
// n = n >> 1;
// count++;
// }
// printf("\n%d", count); // prints 32 as expected
return 0;
}
int wordlength() {
int count;
unsigned int n = ~0;
while( n != 0) {
n = n >> 1;
count++;
}
return count;
}
In your wordlength() function, count is an automatic local scope variable and is not initialized explicitly. So, the initial value is indeterminate.
To quote C11 standard, chapter §6.7.9
If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate. [...]
You're readily applying post-increment onto it. It invokes undefined behavior.
Related, annex §J.2, reasons for undefined behavior,
The value of an object with automatic storage duration is used while it is
indeterminate.
So, your program exhibits UB and not guaranteed to produce any valid result, at all.
Solution: Initialize count to 0.
FWIW, regarding the comment
// if I uncomment the code below
// it then prints 32 like I want
is also a result of UB.
You have to initialize count to 0 or something, or it will have undefined value.

Unexpected behavior of printf() in C [duplicate]

This question already has answers here:
what does the - operator do with char *?
(4 answers)
Closed 9 years ago.
#include <stdio.h>
int main()
{
short int a = 5;
printf("%d" + 1, a);
return 0;
}
The code prints the alphabet enclosed in quotes in printf irrespective of the value and type of variable a. If any other number is added except 1 nothing gets printed.
Why is it so?
Not sure, I would expect it to print just d, of course. That's what happened when I tested it.
If you add more than 1 (or 2) all bets are off and you're getting undefined behavior for passing a random pointer instead of a valid formatting string.
On compiling the above code, you should get a warning like:
[Warning] too many arguments for format [-Wformat-extra-args]
Now remove the printfs argument a.
printf("%d" + 1);
This will print d.
100 101
% d
^
|
Here is the starting address of the string.
%d is a string and its starting address is 100. "%d" + 1 will give you the address 101.
Why you want to do this?
if you want you can do like
do like
printf("%d", a+1);
Try this and you'll understand what unwind is trying to make you understand
#include <stdio.h>
int main()
{
short int a = 5,b = 4;
printf("%d %d" + 4, a,b);
return 0;
}
OUTPUT: d
Since it takes the 4th character inside the double quotes in printf() statement..
If number is 3
OUTPUT: 5
If number is 2
OUTPUT: 5
If number is 1
OUTPUT: d

Resources