Search code examples
catmelstudio

C Function variable changes unexpected


I use the simulator(Atmega 2560) debugger in Atmel studio. When I run the debugger the value F = 30 at the start of the function MoveStraight and it becomes 0 after the first Math/Struct value assignment.

#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) {
    }
}

Why does F change without touching it.


Solution

  • The answer is given by @linuxfansaysReinstateMonica in the comments

    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.