can not check whether a table exists or not in postgresql - sql

I'm writing a C program that connects to a postgreql db.I'm trying to check for a table :
PGresult *re=PQexec(connection, "SELECT to_regclass('fp_stores_data')");
this variable is a global variable. but when I compile the code this error occurs:
db.c:6:20: error: initializer element is not constant
6 | PGresult const *re=PQexec(connection, "SELECT to_regclass('fp_stores_data')");

If this is a global variable, C requires that it be initialized with something known at compile time; if it requires a call to PQexec(), this is a runtime thing and not allowed (as your compiler has told you).
If the variable needs to remain global, best is to initialize the re variable to NULL, and move the actual PQexec() call/assignment into runtime code just after the database connection has been established.
A non-database example: you cannot initialize any static variable with a runtime call, so:
FILE *infile = fopen("myfile.txt", "r"); // NO
int main()
{
infile = fopen("myfile.txt", "r"); // YES
...
It's ok for the variable to be static; it's only the assignment that must be made at runtime.
Alternatively, if the variable is local, it can be initialized with a runtime call.

Related

Nullable variable in Kotlin

I have this code example.
var nullAbleName: String? = null
var v = "I cannot be null"
//! v = nullAbleName // mismatch
nullAbleName = "abc"
v = nullAbleName // Now OK.
nullAbleName is a variable, and its value should be determined in run-time. What is the logic that 2nd assignment of v is OK? Is it that I am lucky because the compiler happens to know the nullAbleName has a value?
This is called smart-casting. The compiler is able to see that the local variable was most recently set to an explicit String, so it treats it as non-null. You may notice that the assignment is colored/highlighted differently by the IDE to show that is employing smart-casting.
This only works with local variables that have not been captured by a closure that modifies them (for instance, creating a callback instance that modifies the value of the local variable). So properties are ineligible for smart casting because they aren't local variables (and could be changed elsewhere) and local variables captured in closures aren't eligible (because they could be changed elsewhere by the closure).

Lua closure reference to variable fails if declared in the same statement declaring the variable

This is a question about closures in Lua. I stumbled across a problem (and workaround) while trying to make an object registrar object as follows:
tracker = {
objList = {},
myRegister = function(self, obj)
table.insert(self.objList, obj)
return "hello"
end,
myInit = function(self)
local i, obj
for i, obj in ipairs(self.objList) do
obj:init()
end
end,
}
-- Note: As written, this does *not* work.
-- It *will* work if I separate the line into two parts as follows:
-- local myvar
-- myvar = tracker:myRegister({
local myvar = tracker:myRegister({
init = function(self)
-- This will generate an error complaining that myvar
-- is a global variable with a "nil" value
print("myvar = " .. myvar)
end,
})
tracker:myInit()
It seems that if I declare the local variable, "myvar", in the same statement which creates a closure, then the local variable is not accessible from the closure. If, however, I merely assign to an already-existing local variable, then that variable is accessible from the closure.
Obviously, I know how to fix this: Just declare myvar separately.
My question, however, is this: Why is this necessary? Is this by design, or is it a bug in the compiler and/or virtual machine? If it's by design, where is it documented? I'm particularly interested in whether this behavior has other implications, and what those might be, and I'm hoping that the documentation (again assuming this is the intended behavior) will shed some light on this.
Yes, this is the intended behavior.
It is documented in the Lua manual §3.5 – Visibility Rules
This feature allows you to write the following code:
print"Beginning of log"
do
local print =
function(...)
print(os.date"%T", ...) -- Here you're invoking global "print"
end
-- inside this do-end block "print" is automatically adding current time
print"Some event"
print"Another event"
end
print"End of log"
In other words, while the shadowing object is being created, the original object is still accessible.
This is quite useful.

how to find out if a c++/cli heap variable has <undefined value>

I've not been using C++ for about 4 years and came back to it a month ago, and that was where I also have first heard about the CLI extension. I still have to get used to it, but this website helps a lot! Thank you!! Anyway, I couldn't find an answer to the following problem:
When I declare a variable
int iStack;
then it is declared but not defined, so it can have any value like
iStack = -858993460
depending on what the value at the stack position is, where the variable is created.
But when I declare a variable on the heap
int^ iHeap
then as far as I know the handle is created but the variable is not instantiated (don't know if you call it instantiation here) or defined and I can only see
iHeap = <Nicht definierter Wert> (which means <undefined value>)
Is there any way to detect if this value is defined?I particularly don't need it for int, but for example for
array<array<c_LocationRef^,2>^>^ arrTest2D_1D = gcnew array<array<c_LocationRef^,2>^>(2);
to find out if the elements of the outer or inner array are instantiated (I'm sure here it is an instantiation ;-) )
arrTest2D_1D = {Length=2}
[0] = {Length=20}
[1] = <Nicht definierter Wert> (=<undefined value>)
As far as I know, the CLR automatically initialise your variables and references in C++ CLI.
In .NET, the Common Language Runtime (CLR) expressly initializes all
variables as soon as they are created. Value types are initialized to
0 and reference types are initialized to null.
To detect if your variable is initialised, you should compare the value of your hat variable to nullptr :
int^ iHeap;
if(iHeap == nullptr){
Console::WriteLine(L"iHeap not initialised");
}
This works on my VS2010 ; it outputs iHeap not initialised
It should work for your specific problem as well (arrays).
By the way, value types are initialised to zero hence your first example should output 0 (I've tested it, and it does output 0) :
int iStack;
Console::WriteLine(L"iStrack = {0}", iStack); // outputs 0
Quote is from codeproject
MSDN page for nullptr
EDIT: Here is an other quote, from Microsoft this time :
When you declare a handle it is automatically initialized with null, so it will not refer to anything.
Quote from MSDN see the paragraph "Tracking Handles"

Statement goto can not cross variable definition?

Suppose these code compiled in g++:
#include <stdlib.h>
int main() {
int a =0;
goto exit;
int *b = NULL;
exit:
return 0;
}
g++ will throw errors:
goto_test.c:10:1: error: jump to label ‘exit’ [-fpermissive]
goto_test.c:6:10: error: from here [-fpermissive]
goto_test.c:8:10: error: crosses initialization of ‘int* b’
It seems like that the goto can not cross pointer definition, but gcc compiles them ok, nothing complained.
After fixed the error, we must declare all the pointers before any of the goto statement, that is to say you must declare these pointers even though you do not need them at the present (and violation with some principles).
What the origin design consideration that g++ forbidden the useful tail-goto statement?
Update:
goto can cross variable (any type of variable, not limited to pointer) declaration, but except those that got a initialize value. If we remove the NULL assignment above, g++ keep silent now. So if you want to declare variables that between goto-cross-area, do not initialize them (and still violate some principles).
Goto can't skip over initializations of variables, because the respective objects would not exist after the jump, since lifetime of object with non-trivial initialization starts when that initialization is executed:
C++11 §3.8/1:
[…] The lifetime of an object of type T begins when:
storage with the proper alignment and size for type T is obtained, and
if the object has non-trivial initialization, its initialization is complete.
C++11 §6.7/3:
It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A
program that jumps from a point where a variable with automatic storage duration is not in scope to a
point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default
constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the
preceding types and is declared without an initializer (8.5).
Since the error mentions [-fpermissive], you can turn it to warning by specifying that compiler flag. This indicates two things. That it used to be allowed (the variable would exist, but be uninitialized after the jump) and that gcc developers believe the specification forbids it.
The compiler only checks whether the variable should be initialized, not whether it's used, otherwise the results would be rather inconsistent. But if you don't need the variable anymore, you can end it's lifetime yourself, making the "tail-goto" viable:
int main() {
int a =0;
goto exit;
{
int *b = NULL;
}
exit:
return 0;
}
is perfectly valid.
On a side-note, the file has extension .c, which suggests it is C and not C++. If you compile it with gcc instead of g++, the original version should compile, because C does not have that restriction (it only has the restriction for variable-length arrays—which don't exist in C++ at all).
There is an easy work-around for those primitive types like int:
// --- original form, subject to cross initialization error. ---
// int foo = 0;
// --- work-around form: no more cross initialization error. ---
int foo; foo = 0;

lua variables scope

I am aware there are other similar topics but could not find an straight answer for my question.
Suppose you have a function such as:
function aFunction()
local aLuaTable = {}
if (something) then
aLuaTable = {}
end
end
For the aLuaTable variable inside the if statement, it is still local right?. Basically what I am asking is if I define a variable as local for the first time and then I use it again and again any number of times will it remain local for the rest of the program's life, how does this work exactly?.
Additionally I read this definition for Lua global variables:
Any variable not in a defined block is said to be in the global scope.
Anything in the global scope is accessible by all inner scopes.
What is it meant by not in a defined block?, my understanding is that if I "declare" a variable anywhere it will always be global is that not correct?.
Sorry if the questions are too simple, but coming from Java and objective-c, lua is very odd to me.
"Any variable not in a defined block is said to be in the global scope."
This is simply wrong, so your confusion is understandable. Looks like you got that from the user wiki. I just updated the page with the correction information:
Any variable that's not defined as local is global.
my understanding is that if I "declare" a variable anywhere it will always be global
If you don't define it as local, it will be global. However, if you then create a local with the same name, it will take precedence over the global (i.e. Lua "sees" locals first when trying to resolve a variable name). See the example at the bottom of this post.
If I define a variable as local for the first time and then I use it again and again any number of times will it remain local for the rest of the program's life, how does this work exactly?
When your code is compiled, Lua tracks any local variables you define and knows which are available in a given scope. Whenever you read/write a variable, if there is a local in scope with that name, it's used. If there isn't, the read/write is translated (at compile time) into a table read/write (via the table _ENV).
local x = 10 -- stored in a VM register (a C array)
y = 20 -- translated to _ENV["y"] = 20
x = 20 -- writes to the VM register associated with x
y = 30 -- translated to _ENV["y"] = 30
print(x) -- reads from the VM register
print(y) -- translated to print(_ENV["y"])
Locals are lexically scoped. Everything else goes in _ENV.
x = 999
do -- create a new scope
local x = 2
print(x) -- uses the local x, so we print 2
x = 3 -- writing to the same local
print(_ENV.x) -- explicitly reference the global x our local x is hiding
end
print(x) -- 999
For the aLuaTable variable inside the if statement, it is still local right?
I don't understand how you're confused here; the rule is the exact same as it is for Java. The variable is still within scope, so therefore it continues to exist.
A local variable is the equivalent of defining a "stack" variable in Java. The variable exists within the block scope that defined it, and ceases to exist when that block ends.
Consider this Java code:
public static void main()
{
if(...)
{
int aVar = 5; //aVar exists.
if(...)
{
aVar = 10; //aVar continues to exist.
}
}
aVar = 20; //compile error: aVar stopped existing at the }
}
A "global" is simply any variable name that is not local. Consider the equivalent Lua code to the above:
function MyFuncName()
if(...) then
local aVar = 5 --aVar exists and is a local variable.
if(...) then
aVar = 10 --Since the most recent declaration of the symbol `aVar` in scope
--is a `local`, this use of `aVar` refers to the `local` defined above.
end
end
aVar = 20 --The previous `local aVar` is *not in scope*. That scope ended with
--the above `end`. Therefore, this `aVar` refers to the *global* aVar.
end
What in Java would be a compile error is perfectly valid Lua code, though it's probably not what you intended.