0

I wrote this code to test static_assert

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <inttypes.h>

#define static_assert _Static_assert

typedef enum {ONE=1, TWO, THREE} num_t;

uint8_t Is_Num_Valid(num_t number){
uint8_t i = 0;
    for(i=1;i<4;i++){
        if(number == i){
            return 1;
        }
    }
    return 0;
}

int main()
{
    num_t number;
    number = ONE;
    printf("%d\n", Is_Num_Valid(number));

    if(Is_Num_Valid(number)){
        static_assert(0, "Number entered is out of boundaries");
    }


    printf("Number is> %d\n", number);
    return 0;
}

Which always results in a compilation error error: static assertion failed: "Number entered is out of boundaries"

why this is not working, it should not execute the body of if() if the condition is 0!!!

4
  • i know i can't use a const int with static_assert as it's != constant_expression, thats why i tried to use this method. Commented Dec 15, 2018 at 11:43
  • What do you expect if it is not valid? Do you expect a compilation error after successful compilation? Commented Dec 15, 2018 at 11:55
  • If you need to evaluate expression at runtime, perhaps you wanted ordinary assert, not static one? static_assert(0) basically instructs compiler to always fail compilation of current translation unit, regardless of where it placed (unless cut out by e.g. preprocessor's #if). Commented Dec 15, 2018 at 12:01
  • thanks guys for help, i already know the difference between assert and static_assert, but the answer of Daniel H clarified what is happening. Commented Dec 15, 2018 at 12:32

1 Answer 1

1

A static_assert happens at compile time, but the decision in an if statement happens at run time. The compiler cannot know that the if clause will be false, and it needs to look at the body of the if statement to know what to do if it isn’t. It sees a static assert, which fails, so generates a compilation error.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Daniel, now i know why :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.