Netbeans 7.3.1 IDE says that "The assigned value is never used" in the indicated line of the following program:
public class JavaTest {
static int f() {
return Math.random() < 0.9 ? 0 : 1;
}
static int g() {
return Math.random() < 0.2 ? 0 : 1;
}
public static void main(String[] args) {
int ret;
while ((ret = f()) == 0) { // Unused assignment???
ret = g();
if (ret != 0)
System.out.println(ret);
}
System.out.println(ret);
}
}
I guess this is a bug in Netbeans, but can someone confirm if they have seen it before?
Edit:
Excellent point and sorry I didn't see it earlier. I agree with you now and I can confirm with your exact code in Eclipse Juno SR2 that there is no warning about unused assignment. Netbeans is in error!
Original:
Netbeans is correct... you immediately assign ret a new value after that line so you might as well just compare f() to 0 e.g. while(f() == 0)
Related
For some reason, one of my JS files is triggering an unsafe-eval Content Security Policy violation on my site. I thought this odd because there is no eval() anywhere in the file. The error happens on the following line:
setTimeout(callSpecific(), (lengthMF * (number.length + 2)));
The only thing I can see here is the arithmetic on the RHS that sets the timeout value. So, I tried:
setTimeout(callSpecific(), (parseInt(lengthMF) * (parseInt(number.length) + 2)));
Same thing. The variables themselves are not even strings - they are defined as:
var lengthMF = 150;
var number = ""; // yes, this is a string but number.length is not!
Why is this triggering a CSP violation? I have other setTimeout()s on the page and this seems to be the only problematic one. The weird thing is replacing the arithmetic expression temporarily with a constant (e.g. 50) does not cause the issue to go away.
If it's necessary, callSpecific() looks something like this:
function callSpecific() {
if (number == 0) {
operatorRing();
} else if (number.length == 2 && number.charAt(1) == 0) {
playReorder();
} else if (number.length == 3) {
//
} else if (number.length <7 || number.length > 11) {
//
} else if (number.length == 11 && (number.charAt(4) == 1 || number.charAt(4) == 0)) {
//
}
}
I have an issue with my n variable. I cannot use n in for loop. Why? n was initialized before for loop. Please, help.
import Foundation
var n: Int
var t: Int
while(true){
var tt = readLine()
t = Int(tt!)!
if (t==0){
break
}
else if ( t < 0){
n = t*(-1)
}
else if(t > 0){
n = t
}
var arr : [[String]] = []
for i in 0..<n*2{
for y in 0..<n*2{
arr[i][y] = "."
}
}
}
A variable may be declared and not immediately initialized, as long as initialization is guaranteed before first use
The error is more subtle than at first glance. You may actually declare a property without initializing it, as long as all program flows leading to its first use ascertain initialization of it.
The issue is with the if, else if and else if block:
var n: Int // declaration
// ...
if (t == 0) {
break
}
else if (t < 0) {
n = t*(-1)
}
else if (t > 0){
n = t
}
// first use
for i in 0..<n*2 { /* ... */ }
Swift cannot not infer that this block is in fact exhaustive, and believes that there is a possibility that none of the above if statements holds, which, in the eyes of the compiler, would lead to the following program state:
program flow has not been broken (break)
and n has not been instantiated
As humans, however, we know that the if - else if - else if block above is indeed exhaustive, and can help the compiler out by simply changing the last if else statement to a simple else statement.
if (t == 0) {
break
}
else if (t < 0) {
n = t*(-1)
}
// if none of the above, t > 0
else {
n = t
}
On another note, the nested array access of non-existing array elements, arr[i][y] = "." will lead to a runtime exception, but this is another issue. In its current form, it looks as if the intent with the nested loops could be replaced with a nested array instantiation:
var arr = [[String]](repeating: [String](repeating: ".", count: 2*n), count: 2*n)
or,
var arr = (0..<2*n).map { _ in [String](repeating: ".", count: 2*n) }
The variable n is only declared, not initialized.
To initialize the variables:
var n: Int = 0
var t: Int = 0
I am downgrading Swift code from Xcode 8.3.1 to Xcode 7.3.1.
The Swift compiler of Xcode 7.3.1 raises
Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
while pointing on line zeroParameterAndPaths.sort {. The code was ok in Xcode 8.3.1.
What's wrong and how to fix it?
class NewConnectingSegmentZeroParameterAndPath {
let step : Int; // 0 = main, 1 = first outline, 2 = second outline
let parameter : CGFloat;
init(step: Int, parameter: CGFloat) {
self.step = step;
self.parameter = parameter;
}
}
var zeroParameterAndPaths : [NewConnectingSegmentZeroParameterAndPath] = [];
// ... some zeroParameterAndPaths .appendContentsOf calls
zeroParameterAndPaths.sort {
return $0.parameter < $1.parameter
|| ($0.parameter == $1.parameter
&& ($0.step == 1 || ($0.step == 0 && $1.step == 2))
)
};
You have two choices. One is simply to do what the error message suggests, i.e. pulling the complex bool apart into separate pieces:
zeroParameterAndPaths.sort {
let bless = ($0.parameter < $1.parameter)
let beq = ($0.parameter == $1.parameter)
let band = ($0.step == 0 && $1.step == 2)
let bor = ($0.step == 1 || band)
let beqandbor = (beq && bor)
return (bless || beqandbor)
};
The other is to provide an explicit in line giving the param types and result type:
zeroParameterAndPaths.sort {
(a:NewConnectingSegmentZeroParameterAndPath, b:NewConnectingSegmentZeroParameterAndPath) -> Bool in
return a.parameter < b.parameter
|| (a.parameter == b.parameter
&& (a.step == 1 || (a.step == 0 && b.step == 2))
)
};
You could also make your class a little bit more helpful and make it implement the condition. The compiler is much less likely to get confused in a function body than in a closure:
class NewConnectingSegmentZeroParameterAndPath {
let step : Int; // 0 = main, 1 = first outline, 2 = second outline
let parameter : CGFloat;
init(step: Int, parameter: CGFloat) {
self.step = step;
self.parameter = parameter;
}
func orderedBefore(_ other: NewConnectingSegmentZeroParameterAndPath) -> Bool
{
return parameter < other.parameter
|| parameter == other.parameter
&& (step == 1 || step == 0 && other.step == 2)
}
}
var zeroParameterAndPaths : [NewConnectingSegmentZeroParameterAndPath] = [];
// ... some zeroParameterAndPaths .appendContentsOf calls
zeroParameterAndPaths.sort { $0.orderedBefore($1) }
Apart from the issue of the type inference engine not being able to quickly resolve such complex bool expressions, such expressions are really hard to follow. I suggest you break it down into something simpler, like so:
zeroParameterAndPaths.sort {
if $0.parameter != $1.parameter { return $0.parameter < $1.parameter ]
if $0.step == 1 { return true }
if $0.step == 0 && $1.step == 2 { return true }
return false
};
There's my attempt at it. I'm not even sure if it's correct, the original expression is pretty hard to follow.
Execution of the following code runs to "!!!" when the compiler is optimized:
int test()
{
volatile uint32_t flag = 0; /* volatile doesnt matter */
flag = 3;
if (flag == 0 )
{
return 0; // !!!
}
else
{
return 1;
}
}
Compiler: IAR Studio C compiler; Platform: SAM4C microcontroller; medium level optimization
Of course, this is already a code, where the original problem has been boiled down.
I cannot understand what the compiler is doing here ...
On the other hand, this works as expected:
int test()
{
volatile uint32_t flag = 0; /* volatile doesnt matter */
int result = 0;
flag = 3;
if (flag == 0 )
{
result = 0;
}
else
{
result = 1; // !!!
}
return result;
}
I spent some more time and observed, that the function indeed returns 1, although the debugger stops at the line with "return 0;".
The problem I ran into was rather related to an uninitialized variable (outside the function), which is not automatically set to zero during optimization.
Apart from the strange behavior in the debugger, the function is correct. Unfortunately, the observation resulted in a misinterpretation.
How can I catch a NSFileHandleOperationException in Swift?
I use fileHandle.readDataToEndOfFile() which calls (according to the documentation) fileHandle.readDataOfLength() which can throw (again according to the documentation) a NSFileHandleOperationException.
How can I catch this exception? I tried
do {
return try fH.readDataToEndOfFile()
} catch NSFileHandleOperationException {
return nil
}
but Xcode says
Warning: No calls to throwing functions occur within 'try' expression
Warning: 'catch' block is unreachable because no errors are thrown in 'do' block
How do I do this? 😄
Edit:
I just decided to use C's good old fopen, fread, fclose as a workaround:
extension NSMutableData {
public enum KCStd$createFromFile$err: ErrorType {
case Opening, Reading, Length
}
public static func KCStd$createFromFile(path: String, offset: Int = 0, length: Int = 0) throws -> NSMutableData {
let fh = fopen(NSString(string: path).UTF8String, NSString(string: "r").UTF8String)
if fh == nil { throw KCStd$createFromFile$err.Opening }
defer { fclose(fh) }
fseek(fh, 0, SEEK_END)
let size = ftell(fh)
fseek(fh, offset, SEEK_SET)
let toRead: Int
if length <= 0 {
toRead = size - offset
} else if offset + length > size {
throw KCStd$createFromFile$err.Length
} else {
toRead = length
}
let buffer = UnsafeMutablePointer<UInt8>.alloc(toRead)
defer {
memset_s(buffer, toRead, 0x00, toRead)
buffer.destroy(toRead)
buffer.dealloc(toRead)
}
let read = fread(buffer, 1, toRead, fh)
if read == toRead {
return NSMutableData(bytes: buffer, length: toRead)
} else {
throw KCStd$createFromFile$err.Reading
}
}
}
KCStd$ (abbreviation for KizzyCode Standard Library) is the prefix because extensions are module-wide. The above code is hereby placed in Public Domain 😊
I'll leave this open because it's nonetheless an interesting question.
The answer seems to be that you can't. If you look at the declarations in FileHandle, you will see comment:
/* The API below may throw exceptions and will be deprecated in a future version of the OS.
Use their replacements instead. */