explicit casts

R

rCs

How sound is the following advice for a C language coding standard?

"Explicitly cast or convert variables. Do not rely on the implicit
conversions."

I have my opinions, but I would like to hear yours.

Thanks,
rCs
 
B

Ben Pfaff

rCs said:
How sound is the following advice for a C language coding standard?

"Explicitly cast or convert variables. Do not rely on the implicit
conversions."

No. Bad idea. Casts are to be avoided when possible.

By the way, casts are always explicit; "explicitly cast" is
redundant.
 
J

J. J. Farrell

How sound is the following advice for a C language coding standard?

"Explicitly cast or convert variables. Do not rely on the implicit
conversions."

I have my opinions, but I would like to hear yours.

Very unsound. It would clutter up the code making it much harder to
read, and is a recipe for hiding bugs from the compiler.

Which of these assignment makes for better code?

char c;

c = 'a';
c = (char)'a';
 
G

Guest

rCs said:
How sound is the following advice for a C language coding standard?

"Explicitly cast or convert variables. Do not rely on the implicit
conversions."

There's clearly absolutely nothing wrong with

char c = 'c';
bool b = false;

and both rely on implicit conversions.
 
T

Thad Smith

rCs said:
How sound is the following advice for a C language coding standard?

"Explicitly cast or convert variables. Do not rely on the implicit
conversions."

I agree with the other posters opposing that as a general rule. Using
casts for assignment to objects with types smaller than the maximum
possible, based on the type of operands and operations within a
statement makes more sense:

char c1, c2;
int i;
long la, lb;

/* assign initial values somehow */

c1 = 'a'; /* can't truncate, no cast */
c2 = c1; /* can't truncate */
c2 = c1 & 0x7f; /* can't truncate */
c2 = (char)(c1 + 5); /* could truncate* */
c2 = (char)i; /* could truncate */
i = (int)(la - lb); /* could truncate */
i = i * 100; /* might overflow, but no cast */

Personally, I probably wouldn't use a cast of c2 = c2 + 5, relying
instead on knowing the range of values to be handled.
 
M

Martin Ambuhl

rCs said:
How sound is the following advice for a C language coding standard?

"Explicitly cast or convert variables. Do not rely on the implicit
conversions."

It's silly advice. Recommending superfluous casts is a dumb idea;
following that recommendation is bad programming.
 

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

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top