All Questions

1887
votes
27answers
154901 views

Do I cast the result of malloc?

In this question, someone suggested in a comment that I should not cast the result of malloc, i.e. int *sieve = malloc(sizeof(int) * length); rather than: int *sieve = (int *) malloc(sizeof(int) *...
1873
votes
6answers
406532 views

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

What are the proper uses of: static_cast dynamic_cast const_cast reinterpret_cast C-style cast (type)value Function-style cast type(value) How does one decide which to use in which specific cases?...
412
votes
5answers
510081 views

How to convert a factor to an integer\numeric without a loss of information?

When I convert a factor to a numeric or integer, I get the underlying level codes, not the values as numbers. f <- factor(sample(runif(5), 20, replace = TRUE)) ## [1] 0.0248644019011408 0.0248644...
3145
votes
11answers
232672 views

Java's +=, -=, *=, /= compound assignment operators

Until today, I thought that for example: i += j; is just a shortcut for: i = i + j; But what if we try this: int i = 5; long j = 8; Then i = i + j; will not compile but i += j; will compile f...
182
votes
10answers
269958 views

Integer division: How do you produce a double?

For this code block: int num = 5; int denom = 7; double d = num / denom; the value of d is 0.0. It can be forced to work by casting: double d = ((double) num) / denom; But is there another way t...
333
votes
18answers
59086 views

Casting vs using the 'as' keyword in the CLR

When programming interfaces, I've found I'm doing a lot of casting or object type conversion. Is there a difference between these two methods of conversion? If so, is there a cost difference or how ...
1384
votes
8answers
519872 views

Regular cast vs. static_cast vs. dynamic_cast

I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e. MyClass *m = (MyClass *)p...
1134
votes
29answers
864958 views

How do I check if a string is a number (float)?

What is the best possible way to check if a string can be represented as a number in Python? The function I currently have right now is: def is_number(s): try: float(s) return T...
535
votes
15answers
106344 views

Direct casting vs 'as' operator?

Consider the following code: void Handler(object o, EventArgs e) { // I swear o is a string string s = (string)o; // 1 //-OR- string s = o as string; // 2 // -OR- string s = o.ToStr...
46
votes
10answers
158267 views

Explanation of "ClassCastException" in Java

I read some articles written on "ClassCastException", but I couldn't get a good idea on that. Is there a good article or what would be a brief explanation?

Previous Next