相关疑难解决方法(0)

函数参数求值顺序

我对调用 C++ 函数时函数参数的计算顺序感到困惑。我可能解释错了,所以请解释是否是这种情况。

例如,Charles Petzold 的传奇著作“Programming Windows”包含如下代码:

// hdc = handle to device context
// x, y = coordinates of where to output text
char szBuffer[64];
TextOut(hdc, x, y, szBuffer, snprintf(szBuffer, 64, "My text goes here"));
Run Code Online (Sandbox Code Playgroud)

现在,最后一个参数是

snprintf(szBuffer, 64, "My text goes here")
Run Code Online (Sandbox Code Playgroud)

它返回写入 char[] szBuffer 的字符数。它还将文本“My text go here”写入 char[] szBuffer。第四个参数是 szBuffer,它包含要写入的文本。但是,我们可以看到 szBuffer 填充在第五个参数中,告诉我们不知何故是表达式

// argument 5
snprintf(szBuffer, 64, "My text goes here")
Run Code Online (Sandbox Code Playgroud)

之前评估过

// argument 4
szBuffer
Run Code Online (Sandbox Code Playgroud)

好的。总是这样吗?评估总是从右到左进行?查看默认调用约定__cdecl

__cdecl 调用约定的主要特点是:

参数从右向左传递,并放置在堆栈中。

堆栈清理由调用者执行。

函数名称通过在其前面加上下划线字符 '_' 来修饰。

(来源: …

c++ winapi calling-convention argument-passing

1
推荐指数
1
解决办法
949
查看次数

当程序执行依赖于执行顺序时,它是未定义的行为吗?

在表达式中

f( g(), h() );
Run Code Online (Sandbox Code Playgroud)

评估顺序g()h()未定义.它只指定一个必须在另一个之前发生.如果g()h()都具有明显的副作用,在程序的执行依赖,这是不确定的行为?

c++ side-effects operator-precedence undefined-behavior

1
推荐指数
1
解决办法
84
查看次数

奇怪的printf行为?

[cprg]$ cat test.c
#include  <stdio.h>
#include <stdlib.h>

int main(int argc,char *argv[])
{
        int i=10;
        printf("i=%d\ni++=%d\n++i=%d\n",i,i++,++i);
        return 0;
}
[cprg]$ make
gcc -g -Wall -o test test.c
test.c: In function ‘main’:
test.c:7: warning: operation on ‘i’ may be undefined
test.c:7: warning: operation on ‘i’ may be undefined
[cprg]$ ./test
i=12
i++=11
++i=12
Run Code Online (Sandbox Code Playgroud)

我不知道为什么会发生这件事.请问有谁可以详细解释我这里发生了什么?

c

0
推荐指数
1
解决办法
460
查看次数

printf with arguments函数返回指向char的指针

嗨,我试着设置一个类似的代码

#include <stdio.h>

struct _data;
typedef struct _data data;
typedef struct _data {
    double x;
    double y;
} data;

const char* data_tostring(data* a) {
    static char buffer[255];
    sprintf(buffer, "%f %f", a->x, a->y);
    return buffer;
}

int main(){
    data a;
    data b;
    a.x = 0;
    a.y = 0;
    b.x = 1;
    b.y = 1;
    printf("%s %s \n", data_tostring(&a), data_tostring(&b));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我期望输出为0 0 1 1,但实际上我得到0 0 0 0.我是否错误地使用static关键字和返回值data_tostring()

谢谢您的帮助.

c printf

0
推荐指数
1
解决办法
44
查看次数

为什么string :: append操作行为奇怪?

看看下面的简单代码:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s("1234567890");
    string::iterator i1 = s.begin();
    string::iterator i2 = s.begin();
    string s1, s2;
    s1.append(i1, ++i1);
    s2.append(++i2, s.end());

    cout << s1 << endl;
    cout << s2 << endl;
}
Run Code Online (Sandbox Code Playgroud)

您对输出的期望是什么?

你会像我一样期望它是:

1
234567890
Run Code Online (Sandbox Code Playgroud)

错误!它是:

234567890
Run Code Online (Sandbox Code Playgroud)

即第一个字符串为空.

前缀增量运算符的接缝在迭代器中存在问题.还是我错过了什么?

c++ linux gcc stl operator-precedence

-3
推荐指数
2
解决办法
278
查看次数