为什么gcc 4.6.1在没有return语句的情况下编译以下函数?
uint32_t& siof_solution() {
static uint32_t example = (uint32_t) 7; // Doesn't really matter
// return example;
}
Run Code Online (Sandbox Code Playgroud)
它回来了1. 我看到了它.
我观察到如果我没有从int返回类型的空函数返回任何值1.但在下面的例子中,它显示4 3 2为o/p(这是静态变量的值在si这里打印?如果我打印si我会得到o/p为2 3 4,与我现在得到的相反.是否存在在这种情况下,与函数的堆栈推送和弹出有关吗?).另外我观察到如果我使用float作为返回类型,那么它打印nan nan nan为o/p.这种行为是编译器依赖的(我已尝试使用gcc和devcpp,观察相同)?这里到底发生了什么?请分享您对此的看法.
#include<iostream>
using namespace std;
int f(int i){
static int si = i;
si = si + i;
///return si;
}
int main(){
cout<<f(1)<<" "<<f(1)<<" "<<f(1);
//cout<<" "<<f(1); //if I uncomment this line then the o/p is: 4 3 2 5, it looks like it's printing the value of si.
}
Run Code Online (Sandbox Code Playgroud)
它看起来像是cout导致反向打印静态变量si值的行为?
在下面的代码部分中,函数中没有return语句,但它仍然编译并给出了正确的答案.这是正常行为吗?
#include <iostream>
int multiply (int x, int y) {
int product = x * y;
}
int main (int argc, char **argv) {
std::cout << multiply(4, 5) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 在C中,当一个函数的返回类型为say int并且我在函数中不包含返回调用时,我只会收到警告.
这可以接受吗?
int foo()
{
int number = 0;
}
Run Code Online (Sandbox Code Playgroud)
返回值是多少?
在赋值时,我必须使用递归二进制搜索算法输出索引而不是True/False而不修改参数.我度过了一段非常艰难的时期,但在诉诸半试错之后,我偶然发现了这个烂摊子:
#include <iostream>
#include <math.h>
#include <climits>
using namespace std;
int BinarySearch(int arr[], int len, int target) {
int temp = 0;
int mid = len/2;
if (len <= 0) return INT_MIN; // not found
if (target == arr[mid]){
return mid; // found
}
if (target < arr[mid]){
temp = BinarySearch(arr, mid, target);
}
else {
temp = mid+1 + BinarySearch(arr+mid+1, len-mid-1, target);
}
}
Run Code Online (Sandbox Code Playgroud)
即使在通过可视化工具运行之后,我也完全不知道它为什么会起作用.它对更改的代码非常敏感,当它无法找到目标时我无法输出-1,所以我至少总是输出一个负数.
我真的不需要它固定,我只是想知道它是如何工作的,因为看起来甚至没有使用递归调用的输出.谢谢.
所以我试着制作一个支付计算器,它会要求用户输入工资,它应该向他们展示所有的东西(他们的净工资,他们的津贴,他们的工资等).我试图让它如此,如果数字他们放入是在一定范围内,其余代码将使用一定数量,但我遇到的问题是只有我的其他if语句正常工作.if语句将执行但也会显示else if语句.你们能帮忙吗?
这是代码的一部分:
///Allowance
int catagory()
{
if ((income <= 150000) && (income >= 80000))
{
allowance = 8000;
printf("\nYour Allowance is: %d", allowance);
}
else if((income <= 79999) && (income >= 55000));
{
allowance = 6500;
printf("\nYour Allowance is: %d", allowance);
}
}
Run Code Online (Sandbox Code Playgroud)