According to the Arduino Reference (int)x translates one variable type to another and forces calculations to be performed in the cast type while int(x) simply converts a value to a int data type.
Am I correct in thinking that (int)x is more capable than int(x)?
Although either will work, I think (int)x is better because consider the case of a cast to unsigned int. You can do this:
(unsigned int)x
but you can't do this:
unsigned int(x)
If you do a mixture of the two your code is harder to read. I do think that int(x) instinctively makes more sense to a beginner who will have already seen that syntax used by functions.
Thanks for getting back to me so quickly. My intention is to break a number into its fractional and integer parts. I thought (possibly incorrectly) that I could explicitly cast my float into an integer to isolate the integer.
float a = 3.142;
float b;
b = int(a);
OR
b = (int)a;
I'm not sure what the difference is between a 'C-style cast' and a functional cast?
Should I be using the function modf? It expects doubles but the Arduino Uno treats doubles and floats the same. I'm unsure how this would work?
Thanks for your input. It seems like a 'C-style cast' has a little more flexibility.
I do agree with you about consistency. It makes your code so much easier to read.
Cheers
Jase
pert:
Although either will work, I think (int)x is better because consider the case of a cast to unsigned int. You can do this:
(unsigned int)x
but you can't do this:
unsigned int(x)
If you do a mixture of the two your code is harder to read. I do think that int(x) instinctively makes more sense to a beginner who will have already seen that syntax used by functions.
pert:
If you do a mixture of the two your code is harder to read. I do think that int(x) instinctively makes more sense to a beginner who will have already seen that syntax used by functions.
When I was teaching this stuff, students got confused with the functional-type cast precisely because it looks like a function. They would ask: "Where can I find the source for the int() function?" I guess it's a matter of preference, but I've been using the K&R style C for almost 40 years now. For me, it's an old-dog-new-trick thing.
I don't think it makes any sense to cast a float to an int, and store the result in a float. If you want the integer portion of a float, just store the float in an int.