Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ error: expected primary-expression before ‘.’ token

I looked at the earlier questions but still i was not satisfied, hence i am posting this. I was trying to compile the C++ code written by someone else.

/*
file1.h
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
    struct
    {   
        unsigned member1;
        unsigned  member2; 
    } str1;

    struct
    {
        unsigned member3;
        unsigned  member4; 
    } str2;

    struct
    {
        unsigned member5;
        unsigned  member6; 
    } str3;
} CONFIG_T;



/* 
file1.c
*/
CONFIG_T  cfg =
{
    .str1 = { 0x01, 0x02 },
    .str2 = { 0x03, 0x04 },
    .str3 = { 0x05, 0x06 }
};

Compiled with std C++11 and i get below error. Why the '.' has been used in code while assigning values ?

home $$  g++ -c -std=gnu++0x  initialze_list.cpp

initialze_list.cpp:34: error: expected primary-expression before ‘.’ token

initialze_list.cpp:35: error: expected primary-expression before ‘.’ token

initialze_list.cpp:36: error: expected primary-expression before ‘.’ token

I was not able to understand the reason for error. Please help.

like image 939
Ashoka K Avatar asked Jul 09 '12 12:07

Ashoka K


People also ask

What is the error expected primary expression before token?

The “expected primary expression before int” error means that you are trying to declare a variable of int data type in the wrong location. It mostly happens when you forget to terminate the previous statement and proceed with declaring another variable.

What is expected expression before token in C?

A1: The error means that the compiler didn't expect you to assign an array to a scalar. When you specify rob_leftcolor[3] = {1.0, 0.0, 0.0}; , you tell compiler, I want you to assign vector of values {1.0, 0.0, 0.0} to 4th element of array rob_leftcolor (counting starts from 0 - 0, 1, 2, 3).

What is primary expression in C programming?

Primary expressions are the building blocks of more complex expressions. They may be constants, identifiers, a Generic selection, or an expression in parentheses.


2 Answers

What you posted is C code, not C++ code (note the .c file extention). However, the following code:

CONFIG_T  cfg =
{
    { 0x01, 0x02 },
    { 0x03, 0x04 },
    { 0x05, 0x06 }
};

should work fine.

You can also read about C++11 initialize lists in the wiki.

like image 123
SingerOfTheFall Avatar answered Sep 17 '22 15:09

SingerOfTheFall


Designated aggregate initializers is a C99 feature, i.e. it is a feature of C language. It is not present in C++.

If you insist on compiling it as C++, you'll have to rewrite the initialization of cfg.

like image 23
AnT Avatar answered Sep 17 '22 15:09

AnT