简体   繁体   English

条件运算和花括号会影响代码吗?

[英]Can conditional operation and curly braces impact the code?

I am wondering if a conditional operator could actually prevent other unrelated code from working. 我想知道条件运算符是否真的可以阻止其他不相关的代码工作。 For example below: 例如下面:

typedef char WCHAR_T;
#define STRLEN(x) strlen(x)
if (argc > 2)
{
    WCHAR *pFileName = argv[1];
    basic_string <WCHAR> strFileName(pFileName, STRLEN(pFileName));
}

In the code above, pFileName, argv[1] and strFileName have nothing to do with the comparison argc > 2 . 在上面的代码中,pFileName,argv [1]和strFileName与argc > 2的比较无关。 Assuming that the command line arguments are perfectly fine. 假设命令行参数很好。 However, this code would not work with that comparison. 但是,此代码不适用于该比较。 Also, even if I change the code to the following format: 另外,即使我将代码更改为以下格式:

typedef char WCHAR_T;
#define STRLEN(x) strlen(x)

{
    WCHAR *pFileName = argv[1];
    basic_string <WCHAR> strFileName(pFileName, STRLEN(pFileName));
}

Still doesn't work. 仍然不起作用。 EDIT: By "doesn't work", I mean compiler gives error message such as "strFileName" was not declared, which means this declaration didn't run at all. 编辑:“不起作用”是指编译器给出错误消息,例如未声明“ strFileName”,这意味着此声明根本没有运行。

I have no idea why the curly braces would have such big impact at the code. 我不知道为什么花括号会对代码产生如此大的影响。 When I get rid of the curly braces, the code works like magic...Could anyone explain this please? 当我去除花括号时,代码就像魔术一样工作……有人可以解释一下吗? Thanks. 谢谢。

Because strFileName only exists within the braces. 因为strFileName仅存在于括号内。 Braces define the scope, local variables are only known within the scope they're defined in. 大括号定义范围,局部变量仅在定义它们的范围内已知。

i guess you're try to use the variable strFileName from somewhere outside the braces, which is not possible. 我猜您正在尝试从括号外的某个地方使用变量strFileName ,这是不可能的。

the { and } braces define a block and variables declared inside are only existent inside this block. {}大括号定义了一个块,并且内部声明的变量仅存在于该块内部。 a workaround would be to declare strFileName outside of the block and assign it's value from inside 一种解决方法是在块外部声明strFileName并从内部分配它的值

typedef char WCHAR_T;
#define STRLEN(x) strlen(x)

basic_string <WCHAR> strFileName;

if (argc > 2)
{
    WCHAR *pFileName = argv[1];
    strFileName.assign(pFileName, STRLEN(pFileName));
}

std::cout << strFileName << std::endl; // should work now

I see a define for WCHAR_T, but what's used in the code is WCHAR. 我看到了WCHAR_T的定义,但是代码中使用的是WCHAR。 Is WCHAR defined anywhere? WCHAR是否在任何地方定义?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM