如果声明可以在内部声明变量吗?

编程入门 行业动态 更新时间:2024-10-24 04:35:17
本文介绍了如果声明可以在内部声明变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图在if语句中声明一个变量,但它表示变量未在范围内声明 我尝试过:

I have tried to declare a variable inside the if statement but it says the the variable is not declared in the scope What I have tried:

#include<iostream> using namespace std; int main() { double y; cout<<"enter y: "; cin>>y; if (x>10) { double x=y*15; cout<<x; return 0; }

推荐答案

是的,它在C ++中没问题,但你的x稍后宣布!!! 但它在你的代码中没什么意义。 Yes it is ok in C++, but your x is declared later!!! But it in your code it makes little sense.

是的没关系 - 你可以在任何一组花括号中声明一个变量,它有它的优点,因为变量在结束时超出了范围。当它超出范围时,就无法引用它。 因此,例如,如果你有一个指针,你分配了内存,使用它然后解除分配它,在的顶部声明它,如果并且释放底部的内存意味着你不能无意中在块外面使用解除分配的指针。 你的例子非常简单,但是是的,它是允许的,而且通常是一个好主意! Yes it's fine - you can declare a variable within any set of curly brackets, and it has it's advantages, because the variable goes out of scope at the closing bracket. And when it goes out of scope, it cannot be referenced. So if for example you had a pointer which you allocated memory, used it and then deallocated it, declaring it at the top of the if and deallocating the memory at the bottom means that you cannot accidently use the deallocated pointer outside the block. Your example is pretty trivial, but yes, it's allowed, and often a good idea!

是的,但这不适用于您的情况。 如果块本身是作用域,并且您定义了作用域,并且变量只能在作用域内访问,而不是在外部,而不是在边界。 所以,我认为你想做的事情是, Yes, but that will not work in your case. if block itself is a scope, and you define a scope and the variables are only accessible inside the scope, not outside, and not at the boundary either. So, I think something you would want to do would be, cin >> y; if (y > 10) { double x = y * 15;

这将起作用,并将测试y的值是否更大。为什么我认为这是正确的方法?因为,您刚刚在 y 变量中输入了输入,现在需要测试用户的输入是否超过10. 否则,你可以这样做,

This would work, and will test if the value of y is greater. Why I think this would be the right approach? Because, you just took input in the y variable, and you would now need to test if the input from user was more than 10. Otherwise, you can do this,

cin >> y; double x = 0; // Initialized with 0, to avoid garbage, and to make my next sentence true if (x > 10) { // x has been already defined x = y * 15;

但请注意,现在你的 if 块永远不会执行,因为它不会超过10因此,如果块永远不会执行。 范围 - cppreference [ ^ ]

But notice, that now your if block would never execute, because it won't be more than 10 and thus if block would never executed. Scope - cppreference[^]

更多推荐

如果声明可以在内部声明变量吗?

本文发布于:2023-11-25 15:43:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630350.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:声明   变量   在内部

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!