C函数变量意外更改
C Function variable changes unexpected
我在 Atmel studio 中使用模拟器 (Atmega 2560) 调试器。
当我 运行 调试器在函数 MoveStraight 开始时的值 F = 30 并且在第一个 Math/Struct 赋值后变为 0。
#include <math.h>
#include <stdio.h>
struct Straight { //Define structure to move straight
long Sx;
long Sy;
long Sz;
unsigned char NX;
unsigned char OCRXAH;
unsigned char OCRXAL;
unsigned char NY;
unsigned char OCRYAH;
unsigned char OCRYAL;
unsigned char NZ;
unsigned char OCRZAH;
unsigned char OCRZAL;
};
struct Straight MoveStraight(unsigned char MoveMode, int X, int Y, int Z, unsigned int F, int Lx, int Ly, int Lz);
struct Straight MoveStraight(unsigned char MoveMode, int X, int Y, int Z, unsigned int F, int Lx, int Ly, int Lz) {
//Here is F = 30
struct Straight StraightMovement;
if (MoveMode == 1) {
StraightMovement.Sx = X * Lx;
//Here is F = 0
StraightMovement.Sy = Y * Ly;
StraightMovement.Sz = Z * Lz;
}
float Fs = (float)F/60;
float St = sqrt(pow(X, 2)+pow(Y, 2)+pow(Z, 2));
float Tt = St/Fs;
//Here comes other code
return StraightMovement;
}
int main(void) {
unsigned char MoveMode = 1;
int X = 5;
int Y = 0;
int Z = 0;
unsigned int F = 30;
int Lx = 6400;
int Ly = 6400;
int Lz = 6400;
struct Straight Move = MoveStraight(MoveMode, X, Y, Z, F, Lx, Ly, Lz);
while (1) {
}
}
为什么不碰F就变了
答案由评论@linuxfansaysReinstateMonica给出
Sometimes the debugger gets confused by the compiler. Maybe the register(s) used to hold F are re-used after F is not been used anymore, and the debugger doesn't notice. Try to disable all the optimizations.
我在 Atmel studio 中使用模拟器 (Atmega 2560) 调试器。 当我 运行 调试器在函数 MoveStraight 开始时的值 F = 30 并且在第一个 Math/Struct 赋值后变为 0。
#include <math.h>
#include <stdio.h>
struct Straight { //Define structure to move straight
long Sx;
long Sy;
long Sz;
unsigned char NX;
unsigned char OCRXAH;
unsigned char OCRXAL;
unsigned char NY;
unsigned char OCRYAH;
unsigned char OCRYAL;
unsigned char NZ;
unsigned char OCRZAH;
unsigned char OCRZAL;
};
struct Straight MoveStraight(unsigned char MoveMode, int X, int Y, int Z, unsigned int F, int Lx, int Ly, int Lz);
struct Straight MoveStraight(unsigned char MoveMode, int X, int Y, int Z, unsigned int F, int Lx, int Ly, int Lz) {
//Here is F = 30
struct Straight StraightMovement;
if (MoveMode == 1) {
StraightMovement.Sx = X * Lx;
//Here is F = 0
StraightMovement.Sy = Y * Ly;
StraightMovement.Sz = Z * Lz;
}
float Fs = (float)F/60;
float St = sqrt(pow(X, 2)+pow(Y, 2)+pow(Z, 2));
float Tt = St/Fs;
//Here comes other code
return StraightMovement;
}
int main(void) {
unsigned char MoveMode = 1;
int X = 5;
int Y = 0;
int Z = 0;
unsigned int F = 30;
int Lx = 6400;
int Ly = 6400;
int Lz = 6400;
struct Straight Move = MoveStraight(MoveMode, X, Y, Z, F, Lx, Ly, Lz);
while (1) {
}
}
为什么不碰F就变了
答案由评论@linuxfansaysReinstateMonica给出
Sometimes the debugger gets confused by the compiler. Maybe the register(s) used to hold F are re-used after F is not been used anymore, and the debugger doesn't notice. Try to disable all the optimizations.