Implicit type casting in C [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
please don't burn me if I'm asking a stupid question but I have problems with implicit type casting in complex statements and I want to learn it.
My code segment is;
int a[]={156, 490, 647};
int b[]={218, 789, 461, 750};
int x=2, y=3;
float result;
result = (float) ( a[x] - b[y]) * 0,05 + 50;
printf ("%.2f", result);
What I meant here was "" (647-750) * 0,05 + 50 ""
So the requested output was:
44,85
What I got is:
-0,00
Sorry if I have done a stupid typo, I think I have made the mistake at placing the (float) but I don't know where to put it. I tried many things but couldn't solve it. Thanks..

Change 0,05 to 0.05.
I think you come from a part of the world where , is used as a decimal separator. But C code always uses . as the decimal separator, irrespective of the compilation locale.
The , in your code is the comma operator.
In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).
So, your expression is evaluated like this:
result = (float) ( a[x] - b[y]) * 0;
And then 05 + 50 is evaluated and thrown away. Or the compiler probably just doesn't bother with it at all and just optimises it away completely.
You can write your assignment statement like this, with no casting:
result = (a[x] - b[y])*0.05 + 50;
When you make this change, the output is as you expect.

Use dot . as decimal seperator instead of comma ,. Try this:
int a[]={156, 490, 647};
int b[]={218, 789, 461, 750};
int x=2, y=3;
float result;
result = (float) ( a[x] - b[y]) * 0.05 + 50;
printf ("%.2f", result);

Related

Getting wrong output for a++ +b according to lexical analysis when the program is printed along with a+++b [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
I wrote the following C program to find the output for a+++b
#include<stdio.h>
int main()
{
int a=5, b=2;
printf("%d",a+++b);
}
And I'm getting the output as 7 which is correct according to lexical analysis.
Apart from that I wrote a separate program to find the output for a++ +b
#include<stdio.h>
int main()
{
int a=5, b=2;
printf("%d",a++ + b);
}
For the above program again I'm getting output as 7 (which is again correct according to lexical analysis)
But when I wrote a program to print the outputs for both a+++b and a++ +b I'm getting different outputs
#include<stdio.h>
int main()
{
int a=5, b=2;
printf("%d",a+++b);
printf("\n%d",a++ + b);
}
The output is 7 for a+++b (which is correct) and 8 for a++ +b (which is wrong).
Can anyone point out the error in the third program?
a++ is post-fix increment. It evaluates to a and increments the variable a by 1 before the enclosing printf() is called in this case(*).
So after the first printf() the value of a is 6.
So what do you now expect from the second printf?
Operators like post-fix ++ are expressions (have a value) and instructions (have an effect). They cause endless confusion bugs and undefined behaviour to novices and bite the most seasoned programmers on the ass from time to time.
(*) These operators are useful and have their place but exactly when these operators take effect is complex sometimes counter intuitive and I recommend you don't use them in complex expressions to begin with or even ever.
They're a bit of a throw back to when compilers didn't optimise code for you and the programmer had to help!
The issue here isn't the space in the second statement, it's the fact you have two of them. After the first statement (to be exact, after a++ is called), the value of a is incremented and is now 6. So a++ + b will clearly return 8. If you omit the first printf call and just call the second one, you'll get 7 as you expect.

Precedence of post increment [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
Can anyone explain what will be the output of following code and why?
int main()
{
int i[] = {3, 5};
int* p = i;
int j = --*p++;
printf("%d\n%d\n", j,*p);
system("pause");
return 0;
}
I'm actually going to answer this question, even though it's true that "the OP simply needs to compile the code and run it", because it isn't obvious to a beginner that this is one of the cases where that gives the right answer. People get dinged all the time on this site for asking why superficially similar code (that does have undefined behavior) gives a surprising answer.
int j = --*p++;
means
int j = *p - 1;
*p = j;
p += 1;
That is, *p (the value that p points to) is decremented, the decremented value is written to j, and then p itself is incremented.
There is no undefined behavior here because the -- and ++ operators in the original form are acting on two different data objects. The expressions that have undefined behavior due to multiple use of the side-effect operators all involve modifying the same data object twice in the same expression ("without an intervening sequence point").
(If you're wondering why the -- applies to *p but the ++ applies only to p, the answer is "because that's what the grammar of the language says. Sorry, this is just one of those things you have to memorize.")

Printing after typecasting with %d or %i gives unexpected outputs [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am rounding off some values and then printing them. When I use %f option, they are printed correctly, but using the %d or %i option (even after casting the rounded values to int) is giving a weird output, and I am not able to figure the why of it out.
Any help is much appreciated!
When I use %f:
i = 0;
while(i < n_shapes)
{
ll_x[i] = (int)round((ll_x[i] - min_x)/pitch_x);
ll_y[i] = (int)round((ll_y[i] - min_y)/pitch_y);
ur_x[i] = (int)round((ur_x[i] - min_x)/pitch_x);
ur_y[i] = (int)round((ur_y[i] - min_y)/pitch_y);
printf("%f,%f,%f,%f\n", ll_x[i], ll_y[i], ur_x[i], ur_y[i]);
i++;
}
Output:
115.000000,94.000000,115.000000,101.000000
116.000000,51.000000,117.000000,58.000000
116.000000,60.000000,117.000000,67.000000
116.000000,69.000000,117.000000,75.000000
116.000000,77.000000,117.000000,84.000000
116.000000,86.000000,117.000000,93.000000
116.000000,94.000000,117.000000,101.000000
Now, with %d (or %i):
i = 0;
while(i < n_shapes)
{
ll_x[i] = (int)round((ll_x[i] - min_x)/pitch_x);
ll_y[i] = (int)round((ll_y[i] - min_y)/pitch_y);
ur_x[i] = (int)round((ur_x[i] - min_x)/pitch_x);
ur_y[i] = (int)round((ur_y[i] - min_y)/pitch_y);
printf("%d,%d,%d,%d\n", ll_x[i], ll_y[i], ur_x[i], ur_y[i]);
i++;
}
Output:
1079590912,0,6,-1
1078788096,0,5,-1
1079033856,0,6,-1
1079164928,0,6,-1
1079312384,0,6,-1
1079459840,0,6,-1
1079590912,0,6,-1
Thank you!
Edit: Yes, I realize that using (int) in the printf gives me the right output. I was curious about the values I got when I didn't do so. What does my output when I use %d without casting inside the printf mean?
This is undefined behavior. You need to use the correct type specifier.
printf cannot verify that the types of parameters that you pass to it for printing match their corresponding format specifiers. The compiler performs type-specific conversions before passing these parameters, so printf expects that for each %f if would find a double (float gets converted to double as well) and for each %d it would find an int. Your code passes a double-converted value for that %d specifier, which causes undefined behavior.
Note that casting a float or a double expression to int before assigning to a float or double variable does not change the representation of the number. All it does is truncating the fractional part. The representation remains the same. In other words, if you do
double x = 12.345;
double y = (int)x;
it is the same as
double x = 12.345;
double y = (double)((int)x);
because in this case the compiler knows the type of variable y, and inserts the missing cast for you.
The first thing to learn about gcc is that you need to turn warnings on explicitly and make them errors using -Wall -Wextra -Werror. These are going to warn you about many useful things if you do not do them exactly right.
Including the format string and wrong argument types as you have here.
I guess the reason why these warning options are not enabled by default is that good-old-perfectly-working-K&R-code would now produce warnings and upset some venerable hackers.

C concepts on arrays [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
int main(){
int arr[2]={30,40};
printf("%dn",i[arr]);
return 0;
}
I found this question in an examination and the given solution is
40
But I think it should give an error since i is undefined.
Or, may be I am missing something.
Please explain me how 40 is the correct answer?
Thanks in advance.
You are correct, the code is wrong. Likely, it is a typo, and the intent was either to define i or to use 1[arr].
Probably it is an error, since i is not defined.
Also, probably the intention of the exercise is to take advantage of the fact that in C, you can write v[ i ] in order to access the #i element of a vector v, or i[ v ].
Both forms are equivalent.Since v[ i ] is translated as *( v + i ), there is actually not any difference between that and *( i + v ), which is what i[ v ] is translated for. This is not a common use, but is nonetheless valid.
Arrays in C, from Wikipedia
In this specific example, 1[arr] would return the expected answer.
I just wonder why they chose 40 instead of 42.
Hope this helps.
i is probably supposed to be given as 1, either in the spoken part of the examination, or in a part that is missing. As written, the question is of course inapplicable since it doesn't compile.
The real point of the question is to test whether the applicant understands that array[index] is equivalent to index[array] and (presumably) why.
In C array[index] = *(array + index) = *(index + array) = index[array]. Assuming i to be 1 (otherwise behavior is undefined), 1[arr] is equivalent to arr[1] and it contains value 40.
Hmm, let's see shall we...
matilda:~ jeremyp$ cat > foo.c
int main(){
int arr[2]={30,40};
printf("%dn",i[arr]);
return 0;
}
matilda:~ jeremyp$ cc foo.c
foo.c:4:5: warning: implicitly declaring library function 'printf' with type 'int (const char *, ...)'
printf("%dn",i[arr]);
^
foo.c:4:5: note: please include the header <stdio.h> or explicitly provide a declaration for 'printf'
foo.c:4:18: error: use of undeclared identifier 'i'
printf("%dn",i[arr]);
^
1 warning and 1 error generated.
Yes indeed, i is undefined. You either need
int i = 1;
before that statement or it isn't an i, it's a 1. Let's try that...
matilda:~ jeremyp$ cat >foo.c
#include <stdio.h> // Stops the warning
int main(){
int arr[2]={30,40};
printf("%d\n",1[arr]); // Also added a \ so we get a line feed.
return 0;
}
matilda:~ jeremyp$ cc foo.c
matilda:~ jeremyp$ ./a.out
40
That works now.

warning: suggest parentheses around assignment used as truth value [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have this code and there is something I do not understand
When I compile the following code:
#include <stdio.h>
#include <stdlib.h>
int main() {
double x=1;
double y=0;
if (x!=y)
{
printf("x!=y\n");
}
if (x=y)
{
printf("x=y\n");
}
return 0;
}
I get get the following warning: warning: suggest parentheses around assignment used as truth value
When I run the programm I get the following output
x!=y
x=y
Why is it printing x=y if if '=' is not to compare but just to put the value there is in y in x.
The compiler is warning you that the result of the expression x = y is used inside a conditional; I mention this even though it does not appear to be related to your actual question because these days, usually it means that there's a typo and the author meant to write == instead.
Regarding the question: since x = y evaluates to y (a double) and y is zero, the result is false because that's what the C standard says should happen. From 6.3.1.2:
When any scalar value is converted to _Bool, the result is 0 if the
value compares equal to 0; otherwise, the result is 1.
So running this code should not print the "equals" message, as indeed it does for me.
if (x!=y) // This tests if x is not the same value as y
{
printf("x!=y\n"); // if x is not the same value as y print this
}
if (x=y) // This assigns x the value of y, the tests the new value of x
{
printf("x=y\n"); // if y was not 0, then print this
}
I think you wanted:
if (x == y) // if x is the same value as y
for your second check
EDIT
After reading your comments I see that you're getting both prints... I'm not sure what compiler you're using, but I can't reproduce your results. Are you sure the code is correctly copied? When I run I only get x!=y as expected as per my explanation.
Run your code with gcc and you'll see it correctly... all I can think of is you're running with some weird non C standard compiler and it's checking the value of x before assigning the y.
You're using the wrong operator: = is an assignment, == is the real comparison (equal). The compiler detects this and warns you just in case this might not be intended (it's far more likely you meant to do a comparison rather than an assignment). This is perfectly valid C (as such it's just a warning, no error). Just to be sure it's intentional, it asks you to add brackets around: if ((x=y)). This won't cause any difference code wise, but it shows that the return value is used on its own and the assignment is just part of it (hard to describe).
Edit:
Both lines are printed due to the assignment:
x!=y evaluates to true - as such the first line is printed.
x=y is an assignment, which is essentially saying that x should take the value of y, which is 0 in this case.
As such the second line shouldn't be written (as 0 evaluates to false), but in general, I'd say it's either a bug or some precision error (this shouldn't happen with a simple assignment of 0, but you never know).
It is an suggestion that perhaps you are making an typo.
Usually, you will have:
if(condition)
In your case the condition is an assignment and hence if always evaluates to true hence the suggestion from compiler.
Daniel Fischer Has answered your question. You are testing to see if x=y. It doesn't, so your first test is true. Then you are assigning y to x, which returns true as it worked and results in outputting the second print statement.
The equality operation is == and = is assignment operator
The correct form is if(x == y) but it will run also it if(x=y)
because in this case, if will first evaluate x=y,and it will assign a value from y to x and after it, the expression will treat as if(x) and it will evaluate then.
and now here if x has 0, then if(x) will treat as false otherwise true.
So, x=y will not get print as output.

Resources