the var doesn't become global but remains local

余生颓废 提交于 2020-01-16 19:39:09

问题


From the following snippet i try to test NewGlobalRef and try to make clsStr global after declaring it in the local scope of if block.

jstring Java_Package_LocalAndGlobalReference_returnGlobalReference
 (JNIEnv *env, jobject obj) {
if(1) {
    printf("In function make global reference\n");
    jclass clsStr ;
    jclass cls = (*env)->FindClass(env,"java/lang/String");
    if( cls == NULL)
        return NULL;
    // create a global reference of clsStr
    clsStr = (*env)->NewGlobalRef(env,cls);
    // Delete the local reference, which is no longer userful
    (*env)->DeleteLocalRef(env,cls);
    if(clsStr == NULL)
        return NULL;
}
 return clsStr; // statement 31
}

When i run the above snippet i get the following errors :

W:\elita\jnitesters\workspace\c\LGR\LGR.c:31: error: 'clsStr' undeclared (first use in this function)
W:\elita\jnitesters\workspace\c\LGR\LGR.c:31: error: (Each undeclared identifier is reported only once
W:\elita\jnitesters\workspace\c\LGR\LGR.c:31: error: for each function it appears in.)

Why do i get the error saying that clsStr is undefined when i have made that var global using the satement clsStr = (*env)->NewGlobalRef(env,cls) ?


回答1:


When you declare a variable in a block (in this case, you declare clsStr in the block if the if(1) { ... } statement), the scope of that variable (and its lifetime) is that block. That means it doesn't exist when you return clsStr after the block.

You can either

  • move the return statement inside the block, or
  • declare the variable clsStr before the if(1) { ... } statement

when i have made that var global using the statement clsStr = (*env)->NewGlobalRef(env,cls)

That is a misunderstanding - you can't make a variable global by assignment; you do that by declaration in the global scope. You can initialize a variable by assignment, but that doesn't have anything to do with its scope.



来源:https://stackoverflow.com/questions/10596766/the-var-doesnt-become-global-but-remains-local

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!