adding a hard coded number to a short creates a build error

  • Thread starter Thread starter TS
  • Start date Start date
T

TS

short x = 1;
//this has build error saying missing conversion
x = x + 2;

Why can't you just add this?

I guess the 1 is a literal that translates to an int32?

How would I accomplish this statement?
 
short x = 1;
//this has build error saying missing conversion
x = x + 2;

Why can't you just add this?

I guess the 1 is a literal that translates to an int32?

How would I accomplish this statement?
x = (short)(x + 2);

IIRC the + operator returns an int unless either operand is a long,
float or double.

rossum
 
Hi TS,

Rossum has given the right answer.

You can declare and initialize a short variable like this example:

short x = 32767;

In the preceding declaration, the integer literal 32767 is implicitly
converted from int to short. If the integer literal does not fit into a
short storage location, a compilation error will occur.

The following assignment statement will produce a compilation error,
because the arithmetic expression on the right-hand side of the assignment
operator evaluates to int by default.

short z = x + y; // Error: no conversion from int to short

To fix this problem, use a cast:

short z = (short)(x + y); // OK: explicit conversion

Hope this helps.
If you have any question, please feel free to let me know.

Sincerely,
Linda Liu
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top